package com.bsoft.gol.hcb.service.prescriptionCirculation;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bsoft.gol.hcb.dao.prescriptionCirculation.*;
import com.bsoft.gol.hcb.serviceEnum.OutpatientTypeEnum;
import com.bsoft.gol.hcb.utils.CommonUtils;
import com.bsoft.gol.hcb.utils.Constants;
import com.bsoft.gol.hcb.utils.DateUtils;
import com.bsoft.gol.hcb.utils.OperationPlatformSignUtil;
import com.bsoft.gol.mpi.model.Card;
import com.bsoft.gol.mpi.model.Certificate;
import com.bsoft.gol.mpi.model.Person;
import com.bsoft.gol.mpi.provider.IMPIProvider;
import com.bsoft.gol.mpi.service.MPIException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.security.cipher.sm.SM4Utils;
import ctd.controller.exception.ControllerException;
import ctd.net.rpc.Client;
import ctd.persistence.annotation.DAOTransaction;
import ctd.spring.boot.annotation.SsdevReference;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.BeanUtils;
import ctd.util.JSONUtils;
import ctd.util.annotation.RpcService;
import hcn.base.BaseDicItem;
import hcn.base.BasePropertyConfig;
import hcn.base.Organization;
import hcn.base.Region;
import hcn.base.drug.export.drugenum.DrugTypeEnum;
import hcn.base.feerule.ExpressFeeRule;
import hcn.base.feerule.ExpressModeRule;
import hcn.base.feerule.ExpressSectionRule;
import hcn.base.feerule.SysBillingRule;
import hcn.bean.UserVo;
import hcn.common.CodeDefinition;
import hcn.enums.CardTypeEnum;
import hcn.ods.PayTrade;
import hcn.protocol.ods.PrecalculatedFeeRequestBean;
import hcn.protocol.ods.UnpayedRecordsRequestBean;
import hcn.protocol.ods.diagnosis.DrugInformation;
import hcn.protocol.ods.diagnosis.FindRecipeSuppliersRequestBean;
import hcn.protocol.ods.diagnosis.Position;
import hcn.protocol.ods.diagnosis.StoresInfo;
import hcn.protocol.ods.newdiagnosis.NewGetPrecalculatedFeeRequestBean;
import hcn.protocol.ods.newdiagnosis.NewGetPrecalculatedFeeResponseBean;
import hcn.protocol.ods.newdiagnosis.NewGetPrecalculatedFeeVO;
import hcn.protocol.ods.newdiagnosis.NewQueryUnPayListResponseBean;
import hcn.protocol.ods.paymentXML.FindRecipeSuppliersXMLReq;
import hcn.protocol.ods.paymentXML.FindRecipeSuppliersXMLResp;
import hcn.protocol.ods.paymentXML.GetDecoctingFeeXMLReq;
import hcn.protocol.ods.paymentXML.GetDecoctingFeeXMLResp;
import hcn.protocol.ods.returnVisit.*;
import hcn.protocol.phr.healthrecord.OutpatientDateilBean;
import hcn.protocol.phr.healthrecord.OutpatientDateilRequestBean;
import hcn.protocol.phr.healthrecord.PrescriptionDrugResponse;
import hcn.protocol.phr.healthrecord.PrescriptionInformationResponse;
import hcn.util.BaseRespUtil;
import hcn.util.BaseResponse;
import hcn.util.ResultCode;
import hcn.util.RpcUserToken;
import org.atag.util.common.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import pcn.bean.consultation.*;
import pcn.bean.express.ExpreeInfoVo;
import pcn.bean.express.QueryDrugOrderExpressInfoListVo;
import pcn.bean.operationPlatform.request.*;
import pcn.bean.operationPlatform.response.*;
import pcn.consultation.ConsultAsk;
import pcn.consultation.ExpressOrder;
import pcn.consultation.OdsDiagnosis;
import pcn.enums.ConsultTypeEnum;
import pcn.enums.FeeTypeEnum;
import pcn.enums.PrescriptionTypeEnum;
import pcn.prescribe.*;
import pcn.prescriptionCirculation.OdsOrderExpenseDetail;
import pcn.prescriptionCirculation.OdsOrderExpenseRecord;
import pcn.prescriptionCirculation.OdsOrderPrescriptionDrug;
import pcn.prescriptionCirculation.OdsOrderPrescriptionInfo;
import pcn.service.consultation.IDrugOrdersService;
import pcn.sign.DoctInfo;
import pcn.sign.ExpressCompany;
import pcn.vo.base.QueryDicContrastListVo;
import pcn.vo.consultation.GetExecuteAddressVo;
import pcn.vo.consultation.QueryDrugOrderDetailVo;
import pcn.vo.consultation.QueryDrugOrderListVo;
import pcn.vo.consultation.QueryPrescriptionNotesVo;
import pcn.vo.prescriptionCirculation.OdsOrderExpenseRecordVo;
import pcn.vo.prescriptionCirculation.OdsOrderPrescriptionInfoVo;
import service.rpc.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

@SsdevService("drugOrderService")
public class DrugOrdersService implements IDrugOrdersService {
    private static final Logger logger = LoggerFactory.getLogger(DrugOrdersService.class);

    @Autowired
    private OdsPrescriptionOrderDAO odsPrescriptionOrderDAO;

    @Autowired
    private OdsOrderToPrescriptionDAO odsOrderToPrescriptionDAO;

    @Autowired
    private ConsultAskServiceIntf consultAskServiceIntf;

    @Autowired
    private OdsExpressInfoDAO odsExpressInfoDAO;
    @Autowired
    private PrescriptionInfoIntf prescriptionInfoIntf;
    @Autowired
    private ExpreeOrderDAO expreeOrderDAO;
    @Autowired
    private DisposalExpenseRecordServiceIntf disposalExpenseRecordServiceIntf;
    @SsdevReference("gol-mpi.mpiProvider")
    private IMPIProvider hcnMpiProvider;
    @Autowired
    private ServiceOpenIntf serviceOpenService;
    @Autowired
    @Qualifier("hcnPayTradeService")
    private PayTradeIntf payTradeService;
    @Autowired
    private RegionIntf regionService;
    @Autowired
    private DiagnosisPayTradeIntf diagnosisPayTradeService;
    @Autowired
    private BaseUserManageUnitIntf baseUserManageUnitService;
    @Autowired
    private DoctorInfoServiceIntf doctorInfoService;
    @Autowired
    private OrganizationInfoIntf organizationInfoService;
    @Autowired
    private ExpressFeeIntf expressFeeService;
    @Autowired
    private DiagnosisInfoIntf diagnosisInfoIntf;
    @Autowired
    private ClinicRecordsIntf clinicRecordsIntf;
    @Autowired
    private ClinicRecordsPlateformIntf clinicRecordsPlateformIntf;
    @Autowired
    private OdsOrderPrescriptionInfoDAO odsOrderPrescriptionInfoDAO;
    @Autowired
    private OdsOrderPrescriptionDrugDAO odsOrderPrescriptionDrugDAO;
    @Autowired
    private OdsOrderExpenseRecordDAO odsOrderExpenseRecordDAO;
    @Autowired
    private OdsOrderExpenseDetailDAO odsOrderExpenseDetailDAO;
    @Autowired
    private DicContrastService dicContrastService;
    @Autowired
    private ExpreeOrderDetailDAO expreeOrderDetailDAO;
    @Autowired
    private RedisUtil redisUtil;

    private static String IMG_UPLOAD_URL;//照片的请求地址前缀

    @Value("${express_query_url}")
    private String expressQueryUrl;


    @Value("${imgUploadUrl}")
    public void setImgUploadUrl(String imgUploadUrl) {
        IMG_UPLOAD_URL = imgUploadUrl;
    }

    /**
     * @description: 获取居民处方药品订单列表
     * @author: chenJij@bsoft.com.cn
     * @date: 2019/12/9 14:50
     * @param: qo
     * @return: pcn.vo.consultation.QueryDrugOrderListVo
     */
    @Override
    @RpcService
    public List<QueryDrugOrderListVo> queryDrugOrderList(QueryDrugOrderListQo qo) throws ControllerException {
        try {
            String boilFlag = "0";
            Integer boilQuentity = 0;//代煎贴数
            int count = 0;
            String mpiId = null;
            UserVo userVo = baseUserManageUnitService.getUserIdByOnline();
            qo.setUserId(userVo.getUserId());
            List<String> feeTypeList = new ArrayList<>();
            feeTypeList.add(FeeTypeEnum.JIANCHA.getTitle());
            feeTypeList.add(FeeTypeEnum.JIANYAN.getTitle());

            //查询用户的订单列表
            List<QueryDrugOrderListVo> queryDrugOrderListVos = odsPrescriptionOrderDAO.findOrderList(qo);
            List<QueryDrugOrderListVo> result = new ArrayList<>();
            if (CommonUtils.isEmpty(queryDrugOrderListVos)) {
                return null;
            }
            for (QueryDrugOrderListVo queryDrugOrderListVo : queryDrugOrderListVos) {
                boolean drugOrderFlag = false;
                BigDecimal drugTotalFee = BigDecimal.ZERO;
                ;
                BigDecimal expanseTotalFee = BigDecimal.ZERO;
                BigDecimal totalFee = BigDecimal.ZERO;
                ;
                BigDecimal boilAmount = BigDecimal.ZERO;
                ;//代煎费
                BigDecimal expressCost = BigDecimal.ZERO;
                ;//快递费
                // 对象数据逻辑，1.根据支付状态来设置到期倒计时, 只有在线支付才会显示倒计时时间
                if (CommonUtils.isNotEmpty(queryDrugOrderListVo.getPayStatus()) && "0".equals(queryDrugOrderListVo.getPayStatus()) && !"0".equals(queryDrugOrderListVo.getPayWay())) {
                    long time = 0;
                    try {
                        time = DateUtils.getCountTimeMillis(new Date(), queryDrugOrderListVo.getPayExpireTime());
                        queryDrugOrderListVo.setPayRemainingSeconds(time);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                //自动确认收货倒计时毫秒数赋值
                if (null != queryDrugOrderListVo.getReceiptExpireTime()) {
                    long time = 0;
                    try {
                        time = DateUtils.getCountTimeMillis(new Date(), queryDrugOrderListVo.getReceiptExpireTime());
                        queryDrugOrderListVo.setReceiptTimeSeconds(time);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
                // 传给APP的状态是合并后的状态orderStatus（实际上的订单状态+实际上支付状态）组合而成，"orderStatus": 0,//订单状态 0 待付款 ；1 待发货 ； 2 待收货  ； 3 支付超时  ; 4 已取消 ;5 已收货 6： 已退款
                //实际上的订单状态orderStatus  1 待发货 ； 2 待收货  ；3已收货  ；4 待自取
                //实际上支付状态payStatus   0：待支付   1：已支付   2：支付超时   3 已取消
                //处理订单状态，合并状态后返回给app
                if ("3".equals(queryDrugOrderListVo.getOrderStatus())) {
                    //已收货
                    queryDrugOrderListVo.setOrderStatus("5");
                } else if ("3".equals(queryDrugOrderListVo.getPayStatus())) {
                    //已取消
                    queryDrugOrderListVo.setOrderStatus("4");
                } else if ("0".equals(queryDrugOrderListVo.getPayStatus())) {
                    //待付款
                    queryDrugOrderListVo.setOrderStatus("0");
                } else if ("2".equals(queryDrugOrderListVo.getPayStatus())) {
                    //支付超时
                    queryDrugOrderListVo.setOrderStatus("3");
                } else if ("1".equals(queryDrugOrderListVo.getOrderStatus())) {
                    //待发货
                    queryDrugOrderListVo.setOrderStatus("1");
                } else if ("2".equals(queryDrugOrderListVo.getOrderStatus())) {
                    //待收货
                    queryDrugOrderListVo.setOrderStatus("2");
                }
                //设置prescribeIdList
                List<OdsOrderToPrescription> odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderToPrescriptionBy(queryDrugOrderListVo.getOrderId());
                List<String> prescribeIdList = new ArrayList<>();
                List<QueryDrugOrderListVo.DrugListBean> drugList = new ArrayList<>();
                List<QueryDrugOrderListVo.ExpanseListBean> expanseListBeans = new ArrayList<>();
                List<QueryDrugOrderListVo.ChineseMedicineListBean> chineseMedicineList = new ArrayList<>();
                if (CommonUtils.isNotEmpty(odsOrderToPrescriptions) && odsOrderToPrescriptions.size() > 0) {
                    OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.get(odsOrderToPrescriptions.get(0).getOrderId());
                    mpiId = odsPrescriptionOrder.getMpiId();
                    for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
                        List<OdsOrderPrescriptionDrug> odsOrderPrescriptionDrugList = null;
                        if (FeeTypeEnum.XIYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CHENGYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CAOYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                            //单个处方id根据类型获得处方明细中的药品
                            OdsOrderPrescriptionInfo odsOrderPrescriptionInfo = odsOrderPrescriptionInfoDAO.getByOrderIdAndPrescriptionInfoId(odsOrderToPrescription.getOrderId(), odsOrderToPrescription.getFeeCode());
                            odsOrderPrescriptionDrugList = odsOrderPrescriptionDrugDAO.findByOrderPrescriptionInfoId(odsOrderPrescriptionInfo.getOrderPrescriptionInfoId());

                            prescribeIdList.add(odsOrderToPrescription.getFeeCode());//处方id

                            if (CommonUtils.isNotEmpty(odsOrderPrescriptionDrugList)) {
                                if (FeeTypeEnum.XIYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CHENGYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) { //西药 中成药
                                    for (OdsOrderPrescriptionDrug odsOrderPrescriptionDrug : odsOrderPrescriptionDrugList) {
                                        QueryDrugOrderListVo.DrugListBean drugListBean = new QueryDrugOrderListVo.DrugListBean();
                                        drugListBean.setDrugName(odsOrderPrescriptionDrug.getDrugName());
                                        drugListBean.setDrugId(String.valueOf(odsOrderPrescriptionDrug.getDrugId()));
                                        drugListBean.setQuantity(odsOrderPrescriptionDrug.getQuantity() == null ? "0.0" : odsOrderPrescriptionDrug.getQuantity() + "");

                                        Double price = odsOrderPrescriptionDrug.getPrice() == null ? 0 : odsOrderPrescriptionDrug.getPrice().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                                        //格式化单价
                                        NumberFormat format = NumberFormat.getInstance();
                                        format.setMaximumFractionDigits(4);
                                        String str = format.format(price);
                                        drugListBean.setPrice(str);

                                        drugListBean.setPackUnit(odsOrderPrescriptionDrug.getPackUnit());
                                        drugListBean.setSpecification(odsOrderPrescriptionDrug.getSpecification());

                                        String feeTypeCode = "";
                                        String feeTypeName = "";
                                        if (FeeTypeEnum.XIYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                                            feeTypeCode = FeeTypeEnum.XIYAO.getTitle();
                                            feeTypeName = FeeTypeEnum.XIYAO.getContext();
                                        } else if (FeeTypeEnum.CHENGYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                                            feeTypeCode = FeeTypeEnum.CHENGYAO.getTitle();
                                            feeTypeName = FeeTypeEnum.CHENGYAO.getContext();
                                        }
                                        drugListBean.setFeeTypeName(feeTypeName);
                                        drugListBean.setFeeTypeCode(feeTypeCode);

                                        drugList.add(drugListBean);
                                        queryDrugOrderListVo.setDrugList(drugList);
                                        count = count + 1;
                                        BigDecimal medicineTotalFee = new BigDecimal(price).multiply(odsOrderPrescriptionDrug.getQuantity() == null ? BigDecimal.valueOf(0) : odsOrderPrescriptionDrug.getQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                        drugTotalFee = drugTotalFee.add(medicineTotalFee);
                                        drugListBean.setAmount(medicineTotalFee.toString());
                                    }

                                } else if (FeeTypeEnum.CAOYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) { //草药
                                    QueryDrugOrderListVo.ChineseMedicineListBean chineseMedicineListBean = new QueryDrugOrderListVo.ChineseMedicineListBean();
                                    List<QueryDrugOrderListVo.ChineseMedicineListBean.MedicineListBean> medicineListBeans = new ArrayList<>();
                                    int totalMedicine = 0;
                                    BigDecimal medicinePrice = BigDecimal.ZERO;
                                    BigDecimal oneMedicinePrice = BigDecimal.ZERO;
                                    for (OdsOrderPrescriptionDrug odsOrderPrescriptionDrug : odsOrderPrescriptionDrugList) {
                                        QueryDrugOrderListVo.ChineseMedicineListBean.MedicineListBean medicineListBean = new QueryDrugOrderListVo.ChineseMedicineListBean.MedicineListBean();
                                        medicineListBean.setDrugId(String.valueOf(odsOrderPrescriptionDrug.getDrugId()));
                                        medicineListBean.setDrugName(odsOrderPrescriptionDrug.getOrgDrugName());
                                        medicineListBean.setSpecification(odsOrderPrescriptionDrug.getSpecification());
                                        medicineListBean.setPackUnit(odsOrderPrescriptionDrug.getPackUnit());
                                        medicineListBean.setQuantity(odsOrderPrescriptionDrug.getQuantity() == null ? "0.0" : odsOrderPrescriptionDrug.getQuantity() + "");
                                        Double price = odsOrderPrescriptionDrug.getPrice() == null ? 0 : odsOrderPrescriptionDrug.getPrice().setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                                        //格式化单价
                                        NumberFormat format = NumberFormat.getInstance();
                                        format.setMaximumFractionDigits(4);
                                        String str = format.format(price);

                                        //一贴的药品总金额
                                        BigDecimal oneMedicineTotalFee = new BigDecimal(price).multiply(odsOrderPrescriptionDrug.getQuantity() == null ? BigDecimal.valueOf(0) : odsOrderPrescriptionDrug.getQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP);
                                        oneMedicinePrice = oneMedicinePrice.add(oneMedicineTotalFee);

                                        //所有贴数的药品金额
                                        BigDecimal numberDrugTotalFee = oneMedicineTotalFee.multiply(new BigDecimal(Double.valueOf(String.valueOf(odsOrderPrescriptionInfo.getNumberOfPackets() == null ? 0 : odsOrderPrescriptionInfo.getNumberOfPackets()))));
                                        //所有贴数草药总金额
                                        medicinePrice = medicinePrice.add(numberDrugTotalFee);
                                        //药品总金额
                                        drugTotalFee = drugTotalFee.add(numberDrugTotalFee);
                                        medicineListBean.setPrice(str);
                                        medicineListBeans.add(medicineListBean);
                                        totalMedicine = totalMedicine + 1;
                                        count = count + 1;
                                    }
                                    chineseMedicineListBean.setMedicinePrice(oneMedicinePrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                                    chineseMedicineListBean.setAmount(medicinePrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                                    chineseMedicineListBean.setTotalMedicine(totalMedicine);
                                    chineseMedicineListBean.setPrescriptionId(odsOrderToPrescription.getFeeCode());
                                    chineseMedicineListBean.setMedicineList(medicineListBeans);
                                    chineseMedicineListBean.setFeeTypeName(FeeTypeEnum.CAOYAO.getContext());
                                    chineseMedicineList.add(chineseMedicineListBean);
                                    queryDrugOrderListVo.setChineseMedicineList(chineseMedicineList);
                                    //计算处方的代煎
                                    chineseMedicineListBean.setNumberOfPackets(odsOrderPrescriptionInfo.getNumberOfPackets());
                                    boilFlag = "1";
                                    boilQuentity = boilQuentity + (odsOrderPrescriptionInfo.getNumberOfPackets() == null ? 0 : odsOrderPrescriptionInfo.getNumberOfPackets());
                                }
                            }
                            drugOrderFlag = true;
                        } else if (!FeeTypeEnum.DJF.getTitle().equals(odsOrderToPrescription.getFeeType()) && !FeeTypeEnum.KDF.getTitle().equals(odsOrderToPrescription.getFeeType())) {//检验或检查
                            OdsOrderExpenseRecord odsOrderExpenseRecord = odsOrderExpenseRecordDAO.getOdsOrderExpenseRecordByOrderIdAndExpenseId(odsOrderToPrescription.getOrderId(), odsOrderToPrescription.getFeeCode());
                            QueryDrugOrderListVo.ExpanseListBean expanseListBean = null;
                            String feeTypeCode = null;
                            String feeTypeName = null;
                            expanseListBean = new QueryDrugOrderListVo.ExpanseListBean();
                           if (CommonUtils.isNotEmpty(odsOrderExpenseRecord)){
                               feeTypeCode = odsOrderExpenseRecord.getBillCategoryCode();
                               feeTypeName = FeeTypeEnum.getDescriptionContext(odsOrderExpenseRecord.getBillCategoryCode());
                                expanseListBean.setItemName(odsOrderExpenseRecord.getItemName());
                                expanseListBean.setTotalFee(odsOrderExpenseRecord.getAmount());
                               expanseListBean.setFeeTypeName(feeTypeName);
                               expanseListBean.setFeeTypeCode(feeTypeCode);
                               if (CommonUtils.isNotEmpty(odsOrderExpenseRecord.getAmount())) {
                                   expanseTotalFee = expanseTotalFee.add(odsOrderExpenseRecord.getAmount());
                               }
                            }
                            expanseListBeans.add(expanseListBean);
                        }

                        if (FeeTypeEnum.DJF.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                            //将代煎费填入最外层，
                            boilAmount = new BigDecimal(odsOrderToPrescription.getTotalFee());

                        }
                        if (FeeTypeEnum.KDF.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                            //将快递填入最外层，
                            expressCost = new BigDecimal(odsOrderToPrescription.getTotalFee());

                        }
                    }
                    queryDrugOrderListVo.setConsultMpiId(mpiId);
                    queryDrugOrderListVo.setBoilAmount(boilAmount.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                    queryDrugOrderListVo.setExpressCost(expressCost.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                    queryDrugOrderListVo.setDrugTotalFee(drugTotalFee.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                    totalFee = totalFee.add(drugTotalFee);
                    totalFee = totalFee.add(boilAmount);
                    totalFee = totalFee.add(expressCost);
                    //门诊类型为空表示这个是从我的入口那边进入药品订单的，不显示检验检查的数据
                    if (!Constants.ZERO.toString().equals(qo.getNoDisplay())) {
                        totalFee = totalFee.add(expanseTotalFee);
                        queryDrugOrderListVo.setExpanseList(expanseListBeans);
                        drugOrderFlag = true;
                    }
                    queryDrugOrderListVo.setTotalFee(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP) + "");
                    queryDrugOrderListVo.setPrescribeIdList(prescribeIdList);

                    queryDrugOrderListVo.setBoilFlag(boilFlag);
                    queryDrugOrderListVo.setBoilQuentity(boilQuentity);
                    queryDrugOrderListVo.setTotal(count);
                    if (drugOrderFlag) {
                        result.add(queryDrugOrderListVo);
                    }
                }
            }
            if(CommonUtils.isEmpty(result)){
                return  null;
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("获取药品订单失败");
        }
    }

    /**
     * @description: 获取药品订单详情
     * @author: chenJij@bsoft.com.cn
     * @date: 2019/12/11 9:40
     */
    @Override
    @RpcService
    public QueryDrugOrderDetailVo queryDrugOrderDetail(QueryDrugOrderDetailQo qo) throws ControllerException {
        try {
            QueryDrugOrderListQo orderListQo = new QueryDrugOrderListQo();
            orderListQo.setConsultId(qo.getOrderId());
            List<QueryDrugOrderListVo> queryDrugOrderListVos = this.queryDrugOrderList(orderListQo);
            if (CommonUtils.isEmpty(queryDrugOrderListVos)) {
                return null;
            }
            QueryDrugOrderListVo queryDrugOrderListVo = queryDrugOrderListVos.get(0);
            Organization organization = organizationInfoService.getOrgDetailByOrgId(queryDrugOrderListVo.getOrgId());
            QueryDrugOrderDetailVo queryDrugOrderDetailVo = new QueryDrugOrderDetailVo();
            BeanUtils.copy(queryDrugOrderListVo, queryDrugOrderDetailVo);
            if (CommonUtils.isNotEmpty(organization)) {
                queryDrugOrderDetailVo.setOrgName(organization.getFullName());
            }
            OdsExpressInfo odsExpressInfo = odsExpressInfoDAO.getOdsExpressInfo(queryDrugOrderDetailVo.getOrderId());
            if (CommonUtils.isNotEmpty(odsExpressInfo)) {
                //发货时间
                queryDrugOrderDetailVo.setDeliverTime(odsExpressInfo.getDeliveryTime());
                queryDrugOrderDetailVo.setReceiptTime(odsExpressInfo.getConfirmReceiptTime());
                queryDrugOrderDetailVo.setStoreType(odsExpressInfo.getStoreType());
                queryDrugOrderDetailVo.setStoreCode(odsExpressInfo.getStoreCode());
                queryDrugOrderDetailVo.setStoreName(odsExpressInfo.getStoreName());
                queryDrugOrderDetailVo.setStorePhone(odsExpressInfo.getStorePhone());
                queryDrugOrderDetailVo.setStoreAddress(odsExpressInfo.getStoreAddress());
                queryDrugOrderDetailVo.setStoreLongitude(odsExpressInfo.getStoreLongitude());
                queryDrugOrderDetailVo.setStoreLatitude(odsExpressInfo.getStoreLatitude());
            }
            //Rpc获取省市区 文字
            try {
                Region province = regionService.queryRegionByCode(queryDrugOrderDetailVo.getReciverProvince());
                logger.info("省信息：" + JSONUtils.toString(province));
                queryDrugOrderDetailVo.setReciverProvinceText(province.getProvince());
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
            try {
                Region city = regionService.queryRegionByCode(queryDrugOrderDetailVo.getReciverCity());
                logger.info("市信息：" + JSONUtils.toString(city));
                queryDrugOrderDetailVo.setReciverCityText(city.getCity());
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }

            try {
                Region district = regionService.queryRegionByCode(queryDrugOrderDetailVo.getReciverDistrict());
                logger.info("区信息：" + JSONUtils.toString(district));
                queryDrugOrderDetailVo.setReciverDistrictText(district.getDistrict());
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }


            return queryDrugOrderDetailVo;
        } catch (ControllerException e) {
            throw new ControllerException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("获取药品订单详情失败");
        }
    }

    /**
     * @description: 保存药品订单
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30 13:32
     * @param: drugIOrdersQo
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     */
    @Override
    @DAOTransaction
    public Map<String, Object> saveDrugOrder(DrugIOrdersQo drugIOrdersQo) throws ControllerException {


        String key = "saveDrugOrder" + JSONUtils.writeValueAsString(drugIOrdersQo);
        if (redisUtil.setnx(key, "1", 3)) {
            logger.info(key + "开始执行");
        } else {
            throw new ControllerException("请勿重复保存订单");
        }


        if (CommonUtils.isEmpty(drugIOrdersQo.getOutpatientType())) {
            throw new ControllerException("就诊类型outpatientType不能为空");
        }

        if (CommonUtils.isEmpty(drugIOrdersQo.getOrgId())) {
            throw new ControllerException("机构标识orgId不能为空");
        }

        if (CommonUtils.isEmpty(drugIOrdersQo.getMpiId())) {
            throw new ControllerException("患者主索引mpiId不能为空");
        }

        if (CommonUtils.isNotEmpty(drugIOrdersQo.getPrescriptionIdList())) {
            long prescriptionInfoCount = odsOrderPrescriptionInfoDAO.getPayedCountByPrescriptionInfoIdList(drugIOrdersQo.getOrgId(), drugIOrdersQo.getPrescriptionIdList());
            if (prescriptionInfoCount > 0) {
                throw new ControllerException("存在已下单的药品，请刷新待支付列表后重新提交");
            }
        }


        if (CommonUtils.isNotEmpty(drugIOrdersQo.getExpenseIdList())) {
            long payedCountByExpenseIdList = odsOrderExpenseRecordDAO.getPayedCountByExpenseIdList(drugIOrdersQo.getOrgId(), drugIOrdersQo.getExpenseIdList());
            if (payedCountByExpenseIdList > 0) {
                throw new ControllerException("存在已下单的医技单，请刷新待支付列表后重新提交");
            }
        }

        try {
            String propertyCode = "";
            if ("1".equals(drugIOrdersQo.getOutpatientType())) {
                //诊间支付是否开通流转
                propertyCode = "013602";
            } else {
                //预支付是否开通流转
                propertyCode = "013604";
            }

            //获取是否开通处方流转的系统参数
            int operationPlatformFlag = 0;
            BasePropertyConfig basePropertyConfig = serviceOpenService.getBasePropertyConfig(propertyCode, drugIOrdersQo.getOrgId());
            if (basePropertyConfig != null) {
                operationPlatformFlag = Integer.parseInt(basePropertyConfig.getPropertyData());
            }

            //若是院外药房，并且开通了流转
            if (1 == operationPlatformFlag && "2".equals(drugIOrdersQo.getStoreType())) {
                if (CommonUtils.isNotEmpty(drugIOrdersQo.getPrescriptionIdList()) && CommonUtils.isNotEmpty(drugIOrdersQo.getExpenseIdList())) {
                    throw new ControllerException("暂不支持检验检查单与处方单无法一起支付");
                }
            }

            //过期的时间差
            Integer payRemainingTime = 1440;
            //获取过期的时间差
            basePropertyConfig = serviceOpenService.getBasePropertyConfig("012211", drugIOrdersQo.getOrgId());
            if (basePropertyConfig != null) {
                payRemainingTime = Integer.parseInt(basePropertyConfig.getPropertyData());
            }

            Person person = hcnMpiProvider.getPerson(drugIOrdersQo.getMpiId());

            //获取问诊记录id集合
            Set<String> consultISet = new HashSet<>();
            //订单处方明细集合
            List<OdsOrderPrescriptionInfoVo> odsOrderPrescriptionInfoList = null;

            if (CommonUtils.isNotEmpty(drugIOrdersQo.getPrescriptionIdList())) {
                //获取订单处方明细集合
                odsOrderPrescriptionInfoList = queryOrderPrescriptionInfoList(drugIOrdersQo);
                //若是线上处方，合并问诊记录标识
                if (CommonUtils.isNotEmpty(odsOrderPrescriptionInfoList) && OutpatientTypeEnum.ON_LINE.getCode().equals(drugIOrdersQo.getOutpatientType())) {
                    for (OdsOrderPrescriptionInfoVo odsOrderPrescriptionInfoVo : odsOrderPrescriptionInfoList) {
                        consultISet.add(odsOrderPrescriptionInfoVo.getConsultId());
                    }
                }

                //若是开通了流转，并且时院外药房
                if (1 == operationPlatformFlag && "2".equals(drugIOrdersQo.getStoreType())) {
                    //上传处方到处方平台
                    uploadToPlatform(drugIOrdersQo, odsOrderPrescriptionInfoList, operationPlatformFlag, person);
                }

            }
            List<OdsOrderExpenseRecordVo> orderExpenseRecordVoList = null;

            //查询检验检查费用记录列表
            if (CommonUtils.isNotEmpty(drugIOrdersQo.getExpenseIdList())) {
                //获取检验检查订单明细集合
                orderExpenseRecordVoList = queryOrderExpenseRecordList(drugIOrdersQo);
                //若是线上检验检查，合并问诊记录标识
                if (CommonUtils.isNotEmpty(orderExpenseRecordVoList) && OutpatientTypeEnum.ON_LINE.getCode().equals(drugIOrdersQo.getOutpatientType())) {
                    for (OdsOrderExpenseRecordVo odsOrderExpenseRecordVo : orderExpenseRecordVoList) {
                        consultISet.add(odsOrderExpenseRecordVo.getConsultId());
                    }
                }

                //若是处置已经有待支付订单，取消原订单
                List<String> orderIdList = odsOrderToPrescriptionDAO.findOrderIdListByfeeCodeList(drugIOrdersQo.getExpenseIdList());
                if (CommonUtils.isNotEmpty(orderIdList)) {
                    odsPrescriptionOrderDAO.updateOdsPrescriptionOrderPayStatus(orderIdList);
                }
            }


            //保存订单记录
            OdsPrescriptionOrder odsPrescriptionOrder = saveOdsPrescriptionOrder(drugIOrdersQo, payRemainingTime);

            //保存物流信息
            OdsExpressInfo odsExpressInfo = saveOdsExpressInfo(drugIOrdersQo, odsPrescriptionOrder.getOrderId(), operationPlatformFlag);

            //保存订单明细
            BigDecimal orderTotalFee = saveOrderDetail(odsPrescriptionOrder, odsOrderPrescriptionInfoList,
                    orderExpenseRecordVoList, drugIOrdersQo, odsExpressInfo);

            //订单总金额
            BigDecimal totalFee = new BigDecimal(orderTotalFee.doubleValue());

            OdsOrderToPrescription odsOrderToPrescription;

            //药品总金额
            odsPrescriptionOrder.setOrderFee(orderTotalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            //保存代煎费
            // 是否代煎  1 代煎
            if ("1".equals(drugIOrdersQo.getBoilFlag())) {
                //订单明细
                odsOrderToPrescription = new OdsOrderToPrescription();
                odsOrderToPrescription.setExpressInfoId(odsExpressInfo.getExpressInfoId());
                odsOrderToPrescription.setFeeType(FeeTypeEnum.DJF.getTitle());
                //实时查询代煎费
                DecocteRequestBean decocteQo = new DecocteRequestBean();
                decocteQo.setPrescriptionIdList(drugIOrdersQo.getPrescriptionIdList());
                decocteQo.setOrgId(drugIOrdersQo.getOrgId());
                DecocteResponseBean decocteResponseBean = queryHerbalMedicineCost(decocteQo);

                odsOrderToPrescription.setTotalFee(decocteResponseBean.getAmount());
                odsOrderToPrescription.setOrderId(odsPrescriptionOrder.getOrderId());
                odsOrderToPrescriptionDAO.save(odsOrderToPrescription);

                totalFee = totalFee.add(new BigDecimal(decocteResponseBean.getAmount()));
            }

            //保存快递费
            if ("1".equals(drugIOrdersQo.getTakeWay())) {
                odsOrderToPrescription = new OdsOrderToPrescription();
                odsOrderToPrescription.setExpressInfoId(odsExpressInfo.getExpressInfoId());
                odsOrderToPrescription.setFeeType(FeeTypeEnum.KDF.getTitle());
                odsOrderToPrescription.setTotalFee(Double.valueOf(drugIOrdersQo.getExpressCost() + ""));
                odsOrderToPrescription.setOrderId(odsPrescriptionOrder.getOrderId());
                odsOrderToPrescriptionDAO.save(odsOrderToPrescription);
            }

            //订单总金额加快递费
            if (null != drugIOrdersQo.getExpressCost()) {
                BigDecimal deliveryAmount = drugIOrdersQo.getExpressCost();
                totalFee = totalFee.add(deliveryAmount);
            }

            //更新订单总金额
            odsPrescriptionOrder.setTotalFee(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            odsPrescriptionOrderDAO.update(odsPrescriptionOrder);

            //创建处方平台业务订单
            if (1 == operationPlatformFlag && "2".equals(drugIOrdersQo.getStoreType())) {
                createPlatformOrder(odsPrescriptionOrder, drugIOrdersQo, odsOrderPrescriptionInfoList, orderExpenseRecordVoList, person);
            }

            //若是线上处方或检验检查，需要同步处方的下单状态
            if (OutpatientTypeEnum.ON_LINE.getCode().equals(drugIOrdersQo.getOutpatientType())) {
                changeConsultAskStatus(drugIOrdersQo, consultISet);
            }

            //返回的结果
            Map<String, Object> map = new HashMap<>();
            map.put("storeType", drugIOrdersQo.getStoreType());
            map.put("storeCode", drugIOrdersQo.getStoreCode());
            map.put("storeName", drugIOrdersQo.getStoreName());
            map.put("storeAddress", drugIOrdersQo.getStoreAddress());
            map.put("storeLongitude", drugIOrdersQo.getStoreLongitude());
            map.put("storeLatitude", drugIOrdersQo.getStoreLatitude());
            map.put("orderId", odsPrescriptionOrder.getOrderId());
            map.put("takeDrugCode", odsPrescriptionOrder.getTakeDrugCode());
            map.put("platformOrderId", odsPrescriptionOrder.getPlatformOrderId());
            map.put("remainingTime", payRemainingTime * 60 * 1000);
            map.put("totalFee", totalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
            return map;

        } catch (ControllerException e) {
            e.printStackTrace();
            throw new ControllerException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("保存订单失败" + e.getMessage());
        }
    }

    /**
     * @description: 同步下处方的处方状态
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30 13:19
     * @param: drugIOrdersQo
     * @param: consultISet
     * @return: void
     */
    private void changeConsultAskStatus(DrugIOrdersQo drugIOrdersQo, Set<String> consultISet) throws ControllerException {
        if (consultISet.size() > 0) {
            for (String consultId : consultISet) {
                //更新问诊记录处方下单状态以及处方是否有药品订单
                ConsultAsk ask = consultAskServiceIntf.getConsultAsksByConsultId(consultId);
                //处方支付，更新处方下单状态
                if (CommonUtils.isNotEmpty(drugIOrdersQo.getPrescriptionIdList())) {
                    //查询是否还存在未下单的处方
                    List<OdsPrescriptionInfo> infos = prescriptionInfoIntf.queryPrescriptionByOrderFlag(consultId);
                    if (CommonUtils.isEmpty(infos)) {
                        //查询是否有已提交处方
                        long countByAuditStatusAndConsultId = prescriptionInfoIntf.getCountByAuditStatusAndConsultId(consultId, "1");
                        if (countByAuditStatusAndConsultId > 0) {
                            ask.setPrescriptionStatus(2);//不能下处方订单
                        }
                    } else {
                        ask.setPrescriptionOrderFlag(1);//标记存在处方订单
                    }
                    consultAskServiceIntf.updateConsultAsk(ask);
                }

                //检验检查支付，更新检验检查下单状态
                if (CommonUtils.isNotEmpty(drugIOrdersQo.getPrescriptionIdList())) {
                    consultAskServiceIntf.updateExamAndCheckStatus(consultId);
                }
            }
        }
    }

    /**
     * @description: 组装检验检查订单明细
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30
     * @param: drugIOrdersQo
     * @return: java.util.List<pcn.vo.prescriptionCirculation.OdsOrderExpenseRecordVo>
     */
    private List<OdsOrderExpenseRecordVo> queryOrderExpenseRecordList(DrugIOrdersQo drugIOrdersQo) throws ControllerException {
        List<OdsOrderExpenseRecordVo> odsOrderExpenseRecordVoList = new ArrayList<>();

        OdsOrderExpenseRecordVo odsOrderExpenseRecordVo;
        List<OdsOrderExpenseDetail> orderExpenseDetailList;
        OdsOrderExpenseDetail odsOrderExpenseDetail;

        if (OutpatientTypeEnum.ON_LINE.getCode().equals(drugIOrdersQo.getOutpatientType())) {
            List<DisposalExpenseRecord> disposalExpenseRecords = disposalExpenseRecordServiceIntf.queryByExpenseIdList(drugIOrdersQo.getExpenseIdList());
            if (CommonUtils.isNotEmpty(disposalExpenseRecords)) {
                for (DisposalExpenseRecord disposalExpenseRecord : disposalExpenseRecords) {
                    odsOrderExpenseRecordVo = new OdsOrderExpenseRecordVo();
                    BeanUtils.copy(disposalExpenseRecord, odsOrderExpenseRecordVo);
                    odsOrderExpenseRecordVo.setState("1");
                    odsOrderExpenseRecordVo.setOrderExpenseId(UUID.randomUUID().toString());

                    BigDecimal totalFee = BigDecimal.ZERO;
                    List<DisposalExpenseDetail> disposalExpenseDetails = disposalExpenseRecordServiceIntf.queryDisposalExpenseDetail(disposalExpenseRecord.getExpenseId());
                    if (CommonUtils.isNotEmpty(disposalExpenseDetails)) {
                        orderExpenseDetailList = new ArrayList<>();

                        for (DisposalExpenseDetail disposalExpenseDetail : disposalExpenseDetails) {
                            odsOrderExpenseDetail = new OdsOrderExpenseDetail();
                            BeanUtils.copy(disposalExpenseDetail, odsOrderExpenseDetail);
                            odsOrderExpenseDetail.setOrderExpenseDetailId(UUID.randomUUID().toString());
                            odsOrderExpenseDetail.setOrderExpenseId(odsOrderExpenseRecordVo.getOrderExpenseId());
                            orderExpenseDetailList.add(odsOrderExpenseDetail);
                            totalFee = totalFee.add(disposalExpenseDetail.getAmount());
                        }
                        odsOrderExpenseRecordVo.setOrderExpenseDetailList(orderExpenseDetailList);
                    }
                    odsOrderExpenseRecordVo.setAmount(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP));
                    odsOrderExpenseRecordVoList.add(odsOrderExpenseRecordVo);
                }
                return odsOrderExpenseRecordVoList;
            }
        } else {

            Organization organization = organizationInfoService.getOrgDetailByOrgId(drugIOrdersQo.getOrgId());
            Person person = null;
            try {
                person = hcnMpiProvider.getPerson(drugIOrdersQo.getMpiId());
            } catch (MPIException e) {
                e.printStackTrace();
            }
            if (null == person) {
                throw new ControllerException("就诊人信息不存在");
            }
            UnpayedRecordsRequestBean request = new UnpayedRecordsRequestBean();
            request.setOrgId(drugIOrdersQo.getOrgId());
            request.setMpiId(drugIOrdersQo.getMpiId());
            request.setOutpatientType(Integer.valueOf(OutpatientTypeEnum.OFF_LINE.getCode()));
            //捡捡检查单没有从HIS获取，能走到这这个方法的，一定是本地的检验检查，线下的检验检查按照原先的流程走
            try {
                String patientId = null;
                List<NewQueryUnPayListResponseBean> unPayedRecordsList = (List<NewQueryUnPayListResponseBean>) Client.rpcInvoke("hcb.diagnosisPayTrade", "queryUnPayedRecordsList", request);
                if (CommonUtils.isNotEmpty(unPayedRecordsList)) {
                    Map<String, NewQueryUnPayListResponseBean.MergingItemsBean> mergingItemsBeanMap = new HashMap<>();
                    for (NewQueryUnPayListResponseBean newQueryUnPayListResponseBean : unPayedRecordsList) {
                        patientId = newQueryUnPayListResponseBean.getPatientCode();
                        for (NewQueryUnPayListResponseBean.MergingItemsBean mergingItemsBean : newQueryUnPayListResponseBean.getMergingItems()) {
                            //若不是西药、中成药、草药，就放置
                            if (!FeeTypeEnum.XIYAO.getContext().equals(mergingItemsBean.getFeeTypeCode())
                                    && !FeeTypeEnum.CHENGYAO.getContext().equals(mergingItemsBean.getFeeTypeCode())
                                    && !FeeTypeEnum.CAOYAO.getContext().equals(mergingItemsBean.getFeeTypeCode())) {
                                mergingItemsBeanMap.put(mergingItemsBean.getFeeNo(), mergingItemsBean);
                            }
                        }
                    }
                    for (String expenseId : drugIOrdersQo.getExpenseIdList()) {
                        NewQueryUnPayListResponseBean.MergingItemsBean mergingItemsBean = mergingItemsBeanMap.get(expenseId);
                        if (null == mergingItemsBean) {
                            throw new ControllerException("找不到费用id为" + expenseId + "的待缴费记录");
                        }

                        BigDecimal totalFee = BigDecimal.ZERO;

                        odsOrderExpenseRecordVo = new OdsOrderExpenseRecordVo();
                        odsOrderExpenseRecordVo.setOrderExpenseDetailList(Lists.newArrayList());
                        odsOrderExpenseRecordVo.setConsultId("");
                        odsOrderExpenseRecordVo.setOrderExpenseId("");
                        odsOrderExpenseRecordVo.setExpenseId(expenseId);
                        odsOrderExpenseRecordVo.setOrderDetailId(0);
                        odsOrderExpenseRecordVo.setOrderId("");
                        odsOrderExpenseRecordVo.setExpenseIdSource(expenseId);
                        odsOrderExpenseRecordVo.setBillCategoryCode(mergingItemsBean.getFeeTypeCode());
                        odsOrderExpenseRecordVo.setOrganizationId(organization.getLocalOrgId());
                        odsOrderExpenseRecordVo.setOrganizationName(organization.getFullName());
                        odsOrderExpenseRecordVo.setPatientId(patientId);
                        odsOrderExpenseRecordVo.setPersonName(person.getPersonName());
                        odsOrderExpenseRecordVo.setAge((byte) 0);
                        odsOrderExpenseRecordVo.setSex(person.getSex());
                        odsOrderExpenseRecordVo.setCardType(person.getCertificate().getCertificateType());
                        odsOrderExpenseRecordVo.setCardNumber(SM4Utils.decryptData_ECB(person.getCertificate().getCertificateNo()));
                        odsOrderExpenseRecordVo.setPatientMedicalCardType("");
                        odsOrderExpenseRecordVo.setPatientMedicalCardNumber("");
                        odsOrderExpenseRecordVo.setEmergencyNumber(mergingItemsBean.getConsultId());
                        odsOrderExpenseRecordVo.setAmount(new BigDecimal("0"));
                        odsOrderExpenseRecordVo.setPayStatus("0");
                        odsOrderExpenseRecordVo.setInvoiceNumber("");
                        odsOrderExpenseRecordVo.setApplicationNo(mergingItemsBean.getApplicationNo());
                        odsOrderExpenseRecordVo.setApplyTime(new Date());
                        odsOrderExpenseRecordVo.setApplyDepartmentId("");
                        odsOrderExpenseRecordVo.setApplyDepartmentName("");
                        odsOrderExpenseRecordVo.setApplyDoctorId("");
                        odsOrderExpenseRecordVo.setApplyDoctorName("");
                        odsOrderExpenseRecordVo.setItemId("");
                        odsOrderExpenseRecordVo.setItemName(mergingItemsBean.getFeeTypeName());
                        odsOrderExpenseRecordVo.setExecutiveStatus("");
                        odsOrderExpenseRecordVo.setExecutiveTime(new Date());
                        odsOrderExpenseRecordVo.setExecutiveDepartmentId("");
                        odsOrderExpenseRecordVo.setExecutiveDepartmentName("");
                        odsOrderExpenseRecordVo.setExecutiveDoctorId("");
                        odsOrderExpenseRecordVo.setExecutiveDoctorName("");
                        odsOrderExpenseRecordVo.setState("1");
                        odsOrderExpenseRecordVo.setExpirationDate(new Date());
                        odsOrderExpenseRecordVo.setDeleteFlag("0");
                        odsOrderExpenseRecordVo.setOrderExpenseId(UUID.randomUUID().toString());

                        List<NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean> detailsItems = mergingItemsBean.getDetailsItems();
                        if (CommonUtils.isNotEmpty(detailsItems)) {
                            orderExpenseDetailList = new ArrayList<>();
                            for (NewQueryUnPayListResponseBean.MergingItemsBean.DetailsItemsBean detailsItem : detailsItems) {
                                odsOrderExpenseDetail = new OdsOrderExpenseDetail();
                                odsOrderExpenseDetail.setExpenseDetailIdSource("");
                                odsOrderExpenseDetail.setItemId("");
                                odsOrderExpenseDetail.setItemName(detailsItem.getItemName());
                                odsOrderExpenseDetail.setItemType((byte) 0);
                                odsOrderExpenseDetail.setNumber(new BigDecimal(detailsItem.getItemNumber()));
                                odsOrderExpenseDetail.setUnit(detailsItem.getUnit());
                                odsOrderExpenseDetail.setPrice(new BigDecimal(detailsItem.getPrice()));
                                odsOrderExpenseDetail.setAmount(new BigDecimal(detailsItem.getAmount()));
                                odsOrderExpenseDetail.setOrderExpenseDetailId(UUID.randomUUID().toString());
                                odsOrderExpenseDetail.setOrderExpenseId(odsOrderExpenseRecordVo.getOrderExpenseId());
                                totalFee = totalFee.add(odsOrderExpenseDetail.getAmount());

                                orderExpenseDetailList.add(odsOrderExpenseDetail);

                            }
                            odsOrderExpenseRecordVo.setAmount(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP));

                            odsOrderExpenseRecordVo.setOrderExpenseDetailList(orderExpenseDetailList);
                        }
                        odsOrderExpenseRecordVoList.add(odsOrderExpenseRecordVo);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return odsOrderExpenseRecordVoList;
    }

    /**
     * @description: 组装处方订单明细
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30
     * @param: drugIOrdersQo
     * @return: java.util.List<pcn.vo.prescriptionCirculation.OdsOrderPrescriptionInfoVo>
     */
    private List<OdsOrderPrescriptionInfoVo> queryOrderPrescriptionInfoList(DrugIOrdersQo drugIOrdersQo) throws ControllerException {
        List<OdsOrderPrescriptionInfoVo> odsOrderPrescriptionInfoList = new ArrayList<>();

        if (OutpatientTypeEnum.ON_LINE.getCode().equals(drugIOrdersQo.getOutpatientType())) {
            //查询线上处方列表
            List<OdsPrescriptionInfo> odsPrescriptionInfoList = prescriptionInfoIntf.queryByFeeNoList(drugIOrdersQo.getPrescriptionIdList());
            if (CommonUtils.isEmpty(odsPrescriptionInfoList)) {
                throw new ControllerException("当前暂无可支付处方");
            } else if (drugIOrdersQo.getPrescriptionIdList().size() != odsPrescriptionInfoList.size()) {
                throw new ControllerException("部分处方不存在，无法支付");
            } else {
                for (OdsPrescriptionInfo odsPrescriptionInfo : odsPrescriptionInfoList) {
                    if ("0".equals(odsPrescriptionInfo.getPrescriptionStatus())) {
                        throw new ControllerException("存在未提交的处方，无法支付");
                    }
                    if ("1".equals(odsPrescriptionInfo.getOrderFlag())) {
                        throw new ControllerException("存在已下单的处方，无法支付");
                    }
                }
            }
            OdsOrderPrescriptionInfoVo odsOrderPrescriptionInfoVo;
            List<OdsOrderPrescriptionDrug> orderPrescriptionDrugList;
            OdsOrderPrescriptionDrug odsOrderPrescriptionDrug;
            for (OdsPrescriptionInfo odsPrescriptionInfo : odsPrescriptionInfoList) {
                odsOrderPrescriptionInfoVo = new OdsOrderPrescriptionInfoVo();
                BeanUtils.copy(odsPrescriptionInfo, odsOrderPrescriptionInfoVo);
                odsOrderPrescriptionInfoVo.setOrderPrescriptionInfoId(UUID.randomUUID().toString());

                //查询线上处方明细
                List<OdsPrescriptionDrug> odsPrescriptionDrugList = prescriptionInfoIntf.findByPrescriptionInfoId(odsPrescriptionInfo.getPrescriptionInfoId());
                if (CommonUtils.isNotEmpty(odsPrescriptionDrugList)) {
                    orderPrescriptionDrugList = new ArrayList<>();
                    for (OdsPrescriptionDrug odsPrescriptionDrug : odsPrescriptionDrugList) {
                        odsOrderPrescriptionDrug = new OdsOrderPrescriptionDrug();
                        BeanUtils.copy(odsPrescriptionDrug, odsOrderPrescriptionDrug);
                        odsOrderPrescriptionDrug.setOrderPrescriptionDrugId(UUID.randomUUID().toString());
                        odsOrderPrescriptionDrug.setOrderPrescriptionInfoId(odsOrderPrescriptionInfoVo.getOrderPrescriptionInfoId());

                        orderPrescriptionDrugList.add(odsOrderPrescriptionDrug);
                    }
                    odsOrderPrescriptionInfoVo.setOrderPrescriptionDrugList(orderPrescriptionDrugList);
                }
                odsOrderPrescriptionInfoList.add(odsOrderPrescriptionInfoVo);
            }
        } else {
            //查询线下处方列表
            Organization organization = organizationInfoService.getOrgDetailByOrgId(drugIOrdersQo.getOrgId());
            //本次订单涉及的就诊序号列表
            List<String> visitIdList = drugIOrdersQo.getVisitIdList().stream().distinct().collect(Collectors.toList());
            if (CommonUtils.isNotEmpty(visitIdList)) {
                List<PrescriptionInformationResponse> informationResponseList = new ArrayList<>();

                for (String visitId : visitIdList) {
                    List<PrescriptionInformationResponse> informationResponses = clinicRecordsPlateformIntf.queryPrescriptionInformationList(organization.getLocalOrgId(), visitId);
                    //遍历问诊的所有处方，取出本次要支付的处方放到集合里
                    if (CommonUtils.isNotEmpty(informationResponses)) {
                        for (PrescriptionInformationResponse informationResponse : informationResponses) {
                            if (drugIOrdersQo.getPrescriptionIdList().contains(informationResponse.getPrescriptionId())) {
                                informationResponse.setEmergencyNumber(visitId);
                                informationResponseList.add(informationResponse);
                            }
                        }
                    }
                }
                //遍历本次要支付的处方，转换数据格式
                if (CommonUtils.isNotEmpty(informationResponseList)) {
                    odsOrderPrescriptionInfoList = changToOdsOrderPrescriptionInfoVo(organization, drugIOrdersQo, informationResponseList);
                }
            }
        }
        return odsOrderPrescriptionInfoList;
    }

    /**
     * @description: 转换HIS的处方返回
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30 11:26
     * @param: informationResponseList
     * @return: java.util.List<pcn.vo.prescriptionCirculation.OdsOrderPrescriptionInfoVo>
     */
    private List<OdsOrderPrescriptionInfoVo> changToOdsOrderPrescriptionInfoVo(Organization organization, DrugIOrdersQo drugIOrdersQo, List<PrescriptionInformationResponse> informationResponseList) {
        if (CommonUtils.isNotEmpty(informationResponseList)) {
            List<OdsOrderPrescriptionInfoVo> odsOrderPrescriptionInfoVoList = new ArrayList<>();
            OdsOrderPrescriptionInfoVo odsOrderPrescriptionInfoVo;
            List<OdsOrderPrescriptionDrug> orderPrescriptionDrugList = null;
            OdsOrderPrescriptionDrug odsOrderPrescriptionDrug;

            for (PrescriptionInformationResponse informationResponse : informationResponseList) {
                //转换处方信息
                odsOrderPrescriptionInfoVo = new OdsOrderPrescriptionInfoVo();
                odsOrderPrescriptionInfoVo.setConsultId(informationResponse.getEmergencyNumber());
                odsOrderPrescriptionInfoVo.setOrderPrescriptionInfoId(UUID.randomUUID().toString());
                odsOrderPrescriptionInfoVo.setPrescriptionInfoId(informationResponse.getPrescriptionId());
                odsOrderPrescriptionInfoVo.setOrgId(drugIOrdersQo.getOrgId());
                odsOrderPrescriptionInfoVo.setOrgName(organization.getFullName());
                odsOrderPrescriptionInfoVo.setDeptId(informationResponse.getVisitDeptCode());
                odsOrderPrescriptionInfoVo.setDeptName(informationResponse.getVisitDeptName());
                odsOrderPrescriptionInfoVo.setPrescriptionId(informationResponse.getPrescriptionId());
                odsOrderPrescriptionInfoVo.setPrescriptionNumber(informationResponse.getPrescriptionNumber());
                odsOrderPrescriptionInfoVo.setMpiId(drugIOrdersQo.getMpiId());
                odsOrderPrescriptionInfoVo.setPrescriptionType(String.valueOf(informationResponse.getDrugType()));
                odsOrderPrescriptionInfoVo.setDiseasesName(informationResponse.getDiagnosisName());
                odsOrderPrescriptionInfoVo.setDoctorId(informationResponse.getDoctorCode());
                odsOrderPrescriptionInfoVo.setDoctorName(informationResponse.getDoctorName());
                odsOrderPrescriptionInfoVo.setLocalDoctorId(informationResponse.getDoctorCode());
                odsOrderPrescriptionInfoVo.setCreateTime(DateUtils.toDate(informationResponse.getPrescriptionDate(), "yyyy-MM-dd HH:mm:ss"));
                odsOrderPrescriptionInfoVo.setAuditDoctorId("");
                odsOrderPrescriptionInfoVo.setAuditor(informationResponse.getAuditor());
                odsOrderPrescriptionInfoVo.setAuditLocalDoctorId("");
                odsOrderPrescriptionInfoVo.setAuditMind(informationResponse.getAuditMind());
                odsOrderPrescriptionInfoVo.setAuditTime(new Date());
                odsOrderPrescriptionInfoVo.setInvoiceNumber("");
                odsOrderPrescriptionInfoVo.setDeleteFlag("0");

                //保存就诊序号
                odsOrderPrescriptionInfoVo.setConsultId(informationResponse.getEmergencyNumber());
                BigDecimal totalFee = BigDecimal.ZERO;

                //转换药品信息
                if (CommonUtils.isNotEmpty(informationResponse.getPrescriptionDrugList())) {
                    orderPrescriptionDrugList = new ArrayList<>();
                    for (PrescriptionDrugResponse prescriptionDrugResponse : informationResponse.getPrescriptionDrugList()) {
                        odsOrderPrescriptionDrug = new OdsOrderPrescriptionDrug();
                        odsOrderPrescriptionDrug.setOrderPrescriptionDrugId(UUID.randomUUID().toString());
                        odsOrderPrescriptionDrug.setOrderPrescriptionInfoId(odsOrderPrescriptionInfoVo.getOrderPrescriptionInfoId());
                        odsOrderPrescriptionDrug.setOrgId(organization.getOrgId());
                        odsOrderPrescriptionDrug.setOrgDrugId(prescriptionDrugResponse.getOrgDrugId());
                        odsOrderPrescriptionDrug.setOrgDrugName(prescriptionDrugResponse.getDrugName());
                        odsOrderPrescriptionDrug.setOrgFactoryId(prescriptionDrugResponse.getFactoryId());
                        odsOrderPrescriptionDrug.setOrgFactoryName(prescriptionDrugResponse.getFactoryName());
                        odsOrderPrescriptionDrug.setDrugId(0);
                        odsOrderPrescriptionDrug.setDrugName(prescriptionDrugResponse.getDrugName());
                        odsOrderPrescriptionDrug.setSpecification(prescriptionDrugResponse.getSpecifications());
                        odsOrderPrescriptionDrug.setDose(new BigDecimal(prescriptionDrugResponse.getDose()));
                        odsOrderPrescriptionDrug.setDoseUnit(prescriptionDrugResponse.getDoseUnit());
                        odsOrderPrescriptionDrug.setFrequencyCode(prescriptionDrugResponse.getFrequencyCode());
                        odsOrderPrescriptionDrug.setFrequencyName(prescriptionDrugResponse.getFrequencyName());
                        odsOrderPrescriptionDrug.setUsageCode(prescriptionDrugResponse.getUsageCode());
                        odsOrderPrescriptionDrug.setUsageName(prescriptionDrugResponse.getUsageName());
                        odsOrderPrescriptionDrug.setDecoctionCode(prescriptionDrugResponse.getDecoctionCode());
                        odsOrderPrescriptionDrug.setDecoctionName(prescriptionDrugResponse.getDecoctionName());
                        odsOrderPrescriptionDrug.setTakeDays(prescriptionDrugResponse.getTakeDays());
                        odsOrderPrescriptionDrug.setQuantity(new BigDecimal(prescriptionDrugResponse.getQuantity()));
                        odsOrderPrescriptionDrug.setPrice(prescriptionDrugResponse.getPrice());
                        odsOrderPrescriptionDrug.setPackUnit(prescriptionDrugResponse.getUnit());
                        odsOrderPrescriptionDrug.setGroupNumber(prescriptionDrugResponse.getGroupNumber());
                        odsOrderPrescriptionDrug.setSortNumber(prescriptionDrugResponse.getSortNumber());
                        odsOrderPrescriptionDrug.setRemark(prescriptionDrugResponse.getRemark());
                        odsOrderPrescriptionDrug.setFootNoteCode(prescriptionDrugResponse.getFootNoteCode());
                        odsOrderPrescriptionDrug.setFootNoteName(prescriptionDrugResponse.getFootNoteName());
                        odsOrderPrescriptionDrug.setTakeWay("");
                        odsOrderPrescriptionDrug.setDrugstorePacking(0);
                        orderPrescriptionDrugList.add(odsOrderPrescriptionDrug);

                        //计算总金额
                        BigDecimal price = prescriptionDrugResponse.getPrice();
                        BigDecimal quantity = new BigDecimal(prescriptionDrugResponse.getQuantity());
                        //贴数为空，就是单价×数量
                        if (null == prescriptionDrugResponse.getNumberOfPackets()) {
                            totalFee = totalFee.add(price.multiply(quantity));
                        } else {
                            //贴数不为空，就是单价×数量×贴数
                            BigDecimal numberOfPackets = new BigDecimal(prescriptionDrugResponse.getNumberOfPackets());
                            totalFee = totalFee.add(price.multiply(quantity).multiply(numberOfPackets));
                        }

                        odsOrderPrescriptionInfoVo.setBoilSign(prescriptionDrugResponse.getBoilSign()==null?null:String.valueOf(prescriptionDrugResponse.getBoilSign()));
                        odsOrderPrescriptionInfoVo.setNumberOfPackets(prescriptionDrugResponse.getNumberOfPackets());
                    }
                    odsOrderPrescriptionInfoVo.setOrderPrescriptionDrugList(orderPrescriptionDrugList);
                }
                odsOrderPrescriptionInfoVo.setTotalPrice(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP));
                odsOrderPrescriptionInfoVoList.add(odsOrderPrescriptionInfoVo);
            }
            return odsOrderPrescriptionInfoVoList;
        }
        return null;
    }

    /**
     * @description: 上传处方到处方平台
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30
     * @param: drugIOrdersQo
     * @param: odsPrescriptionInfos
     * @param: operationPlatformFalg
     * @return: void
     */
    private void uploadToPlatform(DrugIOrdersQo drugIOrdersQo, List<OdsOrderPrescriptionInfoVo> odsOrderPrescriptionInfoList,
                                  int operationPlatformFlag, Person person) throws Exception {

        Organization organization = organizationInfoService.getOrgDetailByOrgId(drugIOrdersQo.getOrgId());
        RecipeUploadReq recipeUploadReq = new RecipeUploadReq();
        //就诊信息
        VisitInfoPro visitInfo = new VisitInfoPro();
        //诊断列表
        List<Diagnoses> diagnosesList = new ArrayList<>();
        visitInfo.setDiagnoses(diagnosesList);
        recipeUploadReq.setVisitInfo(visitInfo);
        //处方信息集合
        List<RecipeInfoPro> recipeInfo = recipeInfoChang(odsOrderPrescriptionInfoList, drugIOrdersQo, null, "1");
        recipeUploadReq.setRecipeInfo(recipeInfo);
        String consultId = null;
        for (OdsOrderPrescriptionInfo odsPrescriptionInfo : odsOrderPrescriptionInfoList) {
            if (consultId == null) {
                consultId = odsPrescriptionInfo.getConsultId();
            } else if (!consultId.equals(odsPrescriptionInfo.getConsultId())) {
                throw new ControllerException("不能同时结算多次就诊的单据");
            }
            visitInfo.setPatientName(person.getPersonName());
            visitInfo.setSex(Integer.valueOf(person.getSex()));
            visitInfo.setPatientPhone(SM4Utils.decryptData_ECB(person.getPhoneNo()));
            visitInfo.setIdcardType(person.getCertificate().getCertificateType());
            visitInfo.setIdcard(SM4Utils.decryptData_ECB(person.getCertificate().getCertificateNo()));
            visitInfo.setOrgIdOutter(organization.getLocalOrgId());
            visitInfo.setOrgNameOutter(organization.getFullName());
            visitInfo.setBirthday(DateUtils.dateFormate(person.getDob(), "yyyy-MM-dd"));
            if (OutpatientTypeEnum.ON_LINE.getCode().equals(drugIOrdersQo.getOutpatientType())) {
                ConsultAsk consultAsk = consultAskServiceIntf.getConsultAsksByConsultId(odsPrescriptionInfo.getConsultId());
                visitInfo.setDeptIdOutter(consultAsk.getDeptId());
                visitInfo.setDeptNameOutter(consultAsk.getDeptName());
                visitInfo.setLocalDoctorId(consultAsk.getDoctorId());
                visitInfo.setVisitIdOutter(consultAsk.getConsultId());
                visitInfo.setVisitTime(consultAsk.getFinishedTime() == null ? consultAsk.getReceptionConfirmTime() : consultAsk.getFinishedTime());

            } else {
                visitInfo.setDeptIdOutter(odsPrescriptionInfo.getDeptId());
                visitInfo.setDeptNameOutter(odsPrescriptionInfo.getDeptName());
                visitInfo.setLocalDoctorId(odsPrescriptionInfo.getDoctorId());
                visitInfo.setVisitIdOutter(odsPrescriptionInfo.getConsultId());
                visitInfo.setVisitTime(odsPrescriptionInfo.getCreateTime());


            }
        }

        //诊断信息
        List<OdsDiagnosis> odsDiagnosisList = null;
        if (consultId != null) {
            if (OutpatientTypeEnum.ON_LINE.getCode().equals(drugIOrdersQo.getOutpatientType())) {
                odsDiagnosisList = diagnosisInfoIntf.queryOdsDiagnosisListByConsultId(consultId);
            } else {
                if (CommonUtils.isNotEmpty(drugIOrdersQo.getVisitIdList())) {
                    odsDiagnosisList = new ArrayList<>();
                    for (String visitId : drugIOrdersQo.getVisitIdList()) {
                        List<OdsDiagnosis> odsDiagnoses = diagnosisInfoIntf.queryHisDiagnosticInfoList(organization.getLocalOrgId(), visitId);
                        if (CommonUtils.isNotEmpty(odsDiagnoses)) {
                            odsDiagnosisList.addAll(odsDiagnoses);
                        }
                    }
                }
            }
        }

        if (!CollectionUtils.isEmpty(odsDiagnosisList)) {
            for (OdsDiagnosis odsDiagnosis : odsDiagnosisList) {
                Diagnoses diagnoses = new Diagnoses();
                diagnoses.setMasterFlag(Integer.valueOf(odsDiagnosis.getMainFlag()));
                diagnoses.setIcdType(odsDiagnosis.getDiagnosisType());
                diagnoses.setIcdName(odsDiagnosis.getDiseasesName());
                diagnoses.setIcdCode(odsDiagnosis.getDiseasesCode());
                diagnoses.setSyndromeCode(odsDiagnosis.getTcmSyndromeCode());
                diagnoses.setSyndromeName(odsDiagnosis.getTcmSyndromeName());
                diagnosesList.add(diagnoses);
            }
        }

        //上传处方到处方平台
        if (1 == operationPlatformFlag && "2".equals(drugIOrdersQo.getStoreType()) && null != recipeUploadReq && CommonUtils.isNotEmpty(recipeUploadReq.getRecipeInfo())) {
            String param = JSONObject.toJSONStringWithDateFormat(recipeUploadReq, JSON.DEFFAULT_DATE_FORMAT);
            try {
                String result = OperationPlatformSignUtil.signPost(param, OperationPlatformSignUtil.UPLOAD);
                JSONObject resultJson = JSONObject.parseObject(result);
                if (ResultCode.SUCCESS == resultJson.getIntValue("code")) {
                    List<RecipeUploadResp> uploadRespList = JSONObject.parseArray(resultJson.getJSONArray("body").toJSONString(), RecipeUploadResp.class);
                    if (!CollectionUtils.isEmpty(uploadRespList)) {
                        for (RecipeUploadResp uploadResp : uploadRespList) {
                            if (uploadResp.getSuccess()) {
                                //若是线上处方，更新状态
                                if (OutpatientTypeEnum.ON_LINE.getCode().equals(drugIOrdersQo.getOutpatientType())) {
                                    List<OdsPrescriptionInfo> infos = prescriptionInfoIntf.queryByFeeNoList(drugIOrdersQo.getPrescriptionIdList());
                                    for (OdsPrescriptionInfo odsPrescriptionInfo : infos) {
                                        if (odsPrescriptionInfo.getPrescriptionNumber().equals(uploadResp.getRecipeIdOutter())) {
                                            odsPrescriptionInfo.setPlatformRecipeId(uploadResp.getRecipeIdOutter());
                                            odsPrescriptionInfo.setPlatformRecipeStatus("1");
                                            odsPrescriptionInfo.setPlatformRecipeFileId(uploadResp.getFileId());
                                            odsPrescriptionInfo.setPlatformRecipeFileUrl(uploadResp.getFileUrl());
                                            //将平台的处方ID及签名文件地址更新至处方表
                                            prescriptionInfoIntf.updateOdsPrescriptionInfo(odsPrescriptionInfo);
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new ControllerException("处方上传失败：" + resultJson.getString("msg"));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //查询运费
        //开通处方流转且选的是院外药房，是快递到家,院外药房的运费使用平台返回的运费，否则用前端传入的运费
        if (1 == operationPlatformFlag && "2".equals(drugIOrdersQo.getStoreType()) && "1".equals(drugIOrdersQo.getTakeWay())) {
            QueryFareReq queryFareReq = new QueryFareReq();
            queryFareReq.setStoreId(drugIOrdersQo.getStoreCode());
            queryFareReq.setRegionCode(drugIOrdersQo.getReciverCity());
            List<RecipeInfoPro> recipeInfo2 = recipeInfoChang(odsOrderPrescriptionInfoList, drugIOrdersQo, null, "2");
            queryFareReq.setPlanInfos(recipeInfo2);
            QueryFareResp queryFareResp = queryFare(queryFareReq);
            if (!StringUtils.isEmpty(queryFareResp.getDeliveryFee())) {
                drugIOrdersQo.setExpressCost(new BigDecimal(queryFareResp.getDeliveryFee()));
            } else {
                throw new ControllerException("获取平台快递费失败失败");
            }
        }
    }

    /**
     * @description: 创建处方平台业务订单
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30
     * @param: odsPrescriptionOrder
     * @param: drugIOrdersQo
     * @return: void
     */
    private void createPlatformOrder(OdsPrescriptionOrder odsPrescriptionOrder, DrugIOrdersQo drugIOrdersQo,
                                     List<OdsOrderPrescriptionInfoVo> odsOrderPrescriptionInfoList,
                                     List<OdsOrderExpenseRecordVo> orderExpenseRecordVoList,
                                     Person person) throws ControllerException {

        SyncOrderReq syncOrderReq = new SyncOrderReq();
        syncOrderReq.setIsPlatformPay(1);
        /*订单配送,订单配送信息节点*/
        OrderReceive orderReceive = new OrderReceive();
        orderReceive.setIdProvince(drugIOrdersQo.getReciverProvince());//省
        orderReceive.setIdCity(drugIOrdersQo.getReciverCity());//市
        orderReceive.setIdDistrict(drugIOrdersQo.getReciverDistrict());//区
        orderReceive.setIdStreet(drugIOrdersQo.getReciverStreet());//镇（街道）
        orderReceive.setReceiverAddress(drugIOrdersQo.getAddress());//详细地址
        orderReceive.setReceiverName(drugIOrdersQo.getReciverName());//收件人姓名
        orderReceive.setReceiverPhone(drugIOrdersQo.getReciverPhone());//收件人手机号
        syncOrderReq.setOrderReceive(orderReceive);

        List<DrugIOrdersQo.StoreDrug> storeDrugList = drugIOrdersQo.getStoreDrugList();
        /*处方信息*/
        List<RecipeInfoPro> recipeInfo = recipeInfoChang(odsOrderPrescriptionInfoList, drugIOrdersQo, storeDrugList, "2");
        List<RecipeInfoPro> recipeInfoList = new ArrayList();
        for (OdsOrderPrescriptionInfoVo prescriptionInfo : odsOrderPrescriptionInfoList) {
            RecipeInfoPro recipeInfoPro = new RecipeInfoPro();
            recipeInfoPro.setRecipeIdOutter(prescriptionInfo.getPrescriptionNumber());//互联网医院处方id
            recipeInfoList.add(recipeInfoPro);
        }
        syncOrderReq.setRecipeInfo(recipeInfo);
        /*订单信息*/
        RecipeOrder recipeOrder = new RecipeOrder();
        //药店ID
        recipeOrder.setStoreIdOutter(drugIOrdersQo.getStoreCode());
        //配送金额，快递费
        recipeOrder.setDeliveryAmount(drugIOrdersQo.getExpressCost().toString());
        //配送方式，1=配送 ,2=自提,与取药方式 1物流配送，2自取 字典一致
        recipeOrder.setDeliveryType(Integer.valueOf(drugIOrdersQo.getTakeWay()));
        //支付途径  0：到院支付•    1：在线支付
        if ("0".equals(drugIOrdersQo.getPayWay())) {
            //2=线下
            recipeOrder.setPayType("2");
        } else {
            //1=线上
            recipeOrder.setPayType("1");
        }
        recipeOrder.setOrderAmount(odsPrescriptionOrder.getTotalFee() + "");//订单总金额
        recipeOrder.setPatientName(person.getPersonName());
        recipeOrder.setBuyerId(person.getMpiId());
        recipeOrder.setUserName(person.getPersonName());
        recipeOrder.setUserPhone(SM4Utils.decryptData_ECB(person.getPhoneNo()));
        Organization organization = organizationInfoService.getOrgDetailByOrgId(drugIOrdersQo.getOrgId());
        recipeOrder.setOrgIdOutter(organization.getLocalOrgId());
        recipeOrder.setPayAmount(odsPrescriptionOrder.getTotalFee() + "");
        syncOrderReq.setRecipeOrder(recipeOrder);

        String param = JSONObject.toJSONStringWithDateFormat(syncOrderReq, JSON.DEFFAULT_DATE_FORMAT);
        try {
            String result = OperationPlatformSignUtil.signPost(param, OperationPlatformSignUtil.SYNC_ORDER);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (ResultCode.SUCCESS == resultJson.getIntValue("code")) {
                SyncOrderResp syncOrderResp = JSONObject.parseObject(resultJson.getJSONObject("data").toJSONString(), SyncOrderResp.class);
                if (syncOrderResp.getSuccess()) {
                    odsPrescriptionOrder.setPlatformOrderId(syncOrderResp.getOrderIdOutter());
                    odsPrescriptionOrder.setTakeDrugCode(syncOrderResp.getOrderNo());
                    odsPrescriptionOrderDAO.update(odsPrescriptionOrder);
                }
            } else {
                for (OdsOrderPrescriptionInfoVo odsPrescriptionInfo : odsOrderPrescriptionInfoList) {
                    logger.info("开始撤回处方:" + odsPrescriptionInfo.getPrescriptionNumber());
                    this.revokeRecipe(odsPrescriptionInfo, 1);
                }
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new ControllerException("订单上传失败：" + resultJson.getString("msg"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @description: 保存订单记录
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30
     * @param: drugIOrdersQo
     * @return: pcn.prescribe.OdsPrescriptionOrder
     */
    private OdsPrescriptionOrder saveOdsPrescriptionOrder(DrugIOrdersQo drugIOrdersQo, Integer payRemainingTime) throws Exception {

        //订单记录
        OdsPrescriptionOrder odsPrescriptionOrder = new OdsPrescriptionOrder();
        //运营平台药店id，获取支付方式需要使用
        odsPrescriptionOrder.setOperatePlatformStoreId(drugIOrdersQo.getOperatePlatformStoreId());
        //运营平台药店名称，获取支付方式需要使用
        odsPrescriptionOrder.setOperatePlatformStoreName(drugIOrdersQo.getOperatePlatformStoreName());
        odsPrescriptionOrder.setOrderId(getUUID());
        odsPrescriptionOrder.setMpiId(drugIOrdersQo.getMpiId());
        UserVo userVo = baseUserManageUnitService.getUserIdByOnline();
        odsPrescriptionOrder.setUserId(userVo.getUserId());
        odsPrescriptionOrder.setOrgId(drugIOrdersQo.getOrgId());
        odsPrescriptionOrder.setSource(drugIOrdersQo.getOutpatientType());
        odsPrescriptionOrder.setPayStatus("0");
        odsPrescriptionOrder.setInvoiceNumber(drugIOrdersQo.getInvoiceNumber());
        odsPrescriptionOrder.setCreateTime(new Date());
        odsPrescriptionOrder.setDeleteFlag("0");
        odsPrescriptionOrder.setPayWay(drugIOrdersQo.getPayWay());

        Date expireTime = new Date();

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(expireTime);
        calendar.add(Calendar.MINUTE, payRemainingTime);
        expireTime = calendar.getTime();
        odsPrescriptionOrder.setPayExpireTime(expireTime);

        Person person = hcnMpiProvider.getPerson(drugIOrdersQo.getMpiId());
        if (null != person) {
            odsPrescriptionOrder.setPersonName(person.getPersonName());
            Card card = hcnMpiProvider.getCard(drugIOrdersQo.getMpiId(), drugIOrdersQo.getOrgId(), CardTypeEnum.MEDICAL_CARD.getTitle());
            if (null != card) {
                odsPrescriptionOrder.setPatientMedicalCardType(card.getCardType());
                odsPrescriptionOrder.setPatientMedicalCardNumber(SM4Utils.decryptData_ECB(card.getCardNo()));
            }
        }

        //抵用券赋值
        if (CommonUtils.isNotEmpty(drugIOrdersQo.getVoucherIdList())) {
            StringBuffer stringBuffer = new StringBuffer();
            for (String voucherId : drugIOrdersQo.getVoucherIdList()) {
                stringBuffer.append(",").append(voucherId);
                odsPrescriptionOrder.setVoucherId(stringBuffer.substring(1));
            }
        }

        return odsPrescriptionOrderDAO.save(odsPrescriptionOrder);
    }

    /**
     * @description: 保存订单配送信息
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30 4:37
     * @param: drugIOrdersQo
     * @param: orderId
     * @param: operationPlatformFalg
     * @return: pcn.prescribe.OdsExpressInfo
     */
    private OdsExpressInfo saveOdsExpressInfo(DrugIOrdersQo drugIOrdersQo, String orderId, int operationPlatformFalg) {

        //订单物流信息
        OdsExpressInfo odsExpressInfo = new OdsExpressInfo();
        odsExpressInfo.setExpressInfoId(getUUID());
        odsExpressInfo.setOrderId(orderId);
        odsExpressInfo.setReciverName(drugIOrdersQo.getReciverName());
        odsExpressInfo.setTelephone(drugIOrdersQo.getReciverPhone());
        odsExpressInfo.setReciverProvince(drugIOrdersQo.getReciverProvince());
        odsExpressInfo.setReciverCity(drugIOrdersQo.getReciverCity());
        odsExpressInfo.setReciverDistrict(drugIOrdersQo.getReciverDistrict());
        odsExpressInfo.setReciverStreet(drugIOrdersQo.getReciverStreet());
        odsExpressInfo.setAddress(drugIOrdersQo.getAddress());
        odsExpressInfo.setTakeWay(drugIOrdersQo.getTakeWay());
        //药店/药房类型：1医院药房  2院外药店
        // 流转到院外，流转方式改为院外
        if (1 == operationPlatformFalg && "2".equals(drugIOrdersQo.getStoreType())) {
            odsExpressInfo.setTransferType("2");
        } else {
            //默认流转到院内
            odsExpressInfo.setTransferType("1");
        }

        odsExpressInfo.setFreightCollectFlag(drugIOrdersQo.getFreightCollectFlag());
        odsExpressInfo.setCreateTime(new Date());
        odsExpressInfo.setDeleteFlag("0");
        odsExpressInfo.setStoreCode(drugIOrdersQo.getStoreCode());
        odsExpressInfo.setStoreName(drugIOrdersQo.getStoreName());
        odsExpressInfo.setStorePhone(drugIOrdersQo.getStorePhone());
        odsExpressInfo.setStoreAddress(drugIOrdersQo.getStoreAddress());
        odsExpressInfo.setStoreLongitude(drugIOrdersQo.getStoreLongitude());
        odsExpressInfo.setStoreLatitude(drugIOrdersQo.getStoreLatitude());
        //保存快递物流信息
        return odsExpressInfoDAO.save(odsExpressInfo);
    }

    /**
     * @description: 保存订单明细
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30
     * @param: odsPrescriptionOrder
     * @param: odsPrescriptionInfos
     * @param: odsOrderExpenseRecords
     * @param: drugIOrdersQo
     * @param: odsExpressInfo
     * @return: java.math.BigDecimal
     */
    private BigDecimal saveOrderDetail(OdsPrescriptionOrder odsPrescriptionOrder, List<OdsOrderPrescriptionInfoVo> odsOrderPrescriptionInfoVoList,
                                       List<OdsOrderExpenseRecordVo> odsOrderExpenseRecords,
                                       DrugIOrdersQo drugIOrdersVo, OdsExpressInfo odsExpressInfo) throws ControllerException {
        String consultType = "";
        BigDecimal orderTotalFee = new BigDecimal(0);
        BigDecimal drugTotalFee;
        OdsOrderToPrescription odsOrderToPrescription = null;
        Map<String, BigDecimal> feeMap = new HashMap<>();
        Map<String, OdsOrderPrescriptionInfoVo> odsOrderPrescriptionInfoMap = new HashMap<>();
        List<OdsOrderPrescriptionDrug> odsPrescriptionDrugs = null;
        //计算药品订单明细
        if (CommonUtils.isNotEmpty(odsOrderPrescriptionInfoVoList)) {
            //计算处方金额
            for (OdsOrderPrescriptionInfoVo odsOrderPrescriptionInfoVo : odsOrderPrescriptionInfoVoList) {
                odsPrescriptionDrugs = odsOrderPrescriptionInfoVo.getOrderPrescriptionDrugList();

                drugTotalFee = new BigDecimal(0);
                //西药 中成药
                if (PrescriptionTypeEnum.WESRERN_MEDICINE.getTitle().equals(odsOrderPrescriptionInfoVo.getPrescriptionType()) ||
                        PrescriptionTypeEnum.CHINESE_PATENT_MEDICINE.getTitle().equals(odsOrderPrescriptionInfoVo.getPrescriptionType())) {
                    for (OdsOrderPrescriptionDrug odsPrescriptionDrug : odsPrescriptionDrugs) {
                        BigDecimal price = odsPrescriptionDrug.getPrice() == null ? BigDecimal.valueOf(0) : odsPrescriptionDrug.getPrice();
                        BigDecimal quantity = odsPrescriptionDrug.getQuantity() == null ? BigDecimal.valueOf(0) : odsPrescriptionDrug.getQuantity();
                        BigDecimal medicineTotalFee = price.multiply(quantity).setScale(2, BigDecimal.ROUND_HALF_UP);
                        //西药或中成药总金额
                        drugTotalFee = drugTotalFee.add(medicineTotalFee);
                        //订单总金额
                        orderTotalFee = orderTotalFee.add(medicineTotalFee);
                    }
                    feeMap.put(odsOrderPrescriptionInfoVo.getOrderPrescriptionInfoId(), drugTotalFee);
                    odsOrderPrescriptionInfoMap.put(odsOrderPrescriptionInfoVo.getPrescriptionId(), odsOrderPrescriptionInfoVo);
                    //草药
                } else if (PrescriptionTypeEnum.CHINESE_MEDICINE.getTitle().equals(odsOrderPrescriptionInfoVo.getPrescriptionType())) {
                    for (OdsOrderPrescriptionDrug odsPrescriptionDrug : odsPrescriptionDrugs) {
                        //单价
                        BigDecimal price = odsPrescriptionDrug.getPrice() == null ? BigDecimal.valueOf(0) : odsPrescriptionDrug.getPrice();
                        //数量
                        BigDecimal quantity = odsPrescriptionDrug.getQuantity() == null ? BigDecimal.valueOf(0) : odsPrescriptionDrug.getQuantity();
                        //处方贴数
                        Integer numberOfPackets = odsOrderPrescriptionInfoVo.getNumberOfPackets() == null ? 0 : odsOrderPrescriptionInfoVo.getNumberOfPackets();
                        BigDecimal medicineTotalFee = price.multiply(quantity).multiply(new BigDecimal(numberOfPackets)).setScale(2, BigDecimal.ROUND_HALF_UP);
                        //草药总金额 单个草药总金额 乘以 处方贴数
                        drugTotalFee = drugTotalFee.add(medicineTotalFee);
                        //订单总金额
                        orderTotalFee = orderTotalFee.add(medicineTotalFee);
                    }
                    feeMap.put(odsOrderPrescriptionInfoVo.getOrderPrescriptionInfoId(), drugTotalFee);
                    odsOrderPrescriptionInfoMap.put(odsOrderPrescriptionInfoVo.getPrescriptionId(), odsOrderPrescriptionInfoVo);

                }
            }

            //保存处方明细
            for (OdsOrderPrescriptionInfoVo odsOrderPrescriptionInfoVo : odsOrderPrescriptionInfoVoList) {
                //订单明细
                odsOrderToPrescription = new OdsOrderToPrescription();
                //云门诊
                if (OutpatientTypeEnum.ON_LINE.getCode().equals(drugIOrdersVo.getOutpatientType())) {
                    OdsPrescriptionInfo odsPrescriptionInfo = prescriptionInfoIntf.getOdsPrescriptionInfo(odsOrderPrescriptionInfoVo.getPrescriptionInfoId());
                    ConsultAsk consultAsk = consultAskServiceIntf.getConsultAsksByConsultId(odsPrescriptionInfo.getConsultId());
                    odsOrderToPrescription.setConsultType(consultAsk.getConsultType());
                    odsOrderToPrescription.setConsultId(consultAsk.getConsultId());

                    //标记处方有药品订单
                    odsPrescriptionInfo.setOrderFlag("1");
                    prescriptionInfoIntf.updateOdsPrescriptionInfo(odsPrescriptionInfo);
                } else {
                    //诊间支付问诊类型写死
                    odsOrderToPrescription.setConsultType(ConsultTypeEnum.CLINIC.getTitle());
                    //诊间支付的consultId就是就诊序号
                    odsOrderToPrescription.setConsultId(odsOrderPrescriptionInfoVo.getConsultId());
                }

                odsOrderToPrescription.setOrderId(odsPrescriptionOrder.getOrderId());
                odsOrderToPrescription.setExpressInfoId(odsExpressInfo.getExpressInfoId());
                if (CommonUtils.isNotEmpty(odsOrderPrescriptionInfoVo)) {

                    String feeType = "";
                    if (DrugTypeEnum.XIYAO.getCode().equals(odsOrderPrescriptionInfoVo.getPrescriptionType())) {
                        feeType = FeeTypeEnum.XIYAO.getTitle();
                    } else if (DrugTypeEnum.ZHONGYAO.getCode().equals(odsOrderPrescriptionInfoVo.getPrescriptionType())) {
                        feeType = FeeTypeEnum.CHENGYAO.getTitle();
                    } else if (DrugTypeEnum.CAOYAO.getCode().equals(odsOrderPrescriptionInfoVo.getPrescriptionType())) {
                        feeType = FeeTypeEnum.CAOYAO.getTitle();
                    }
                    odsOrderToPrescription.setFeeType(feeType);
                    //云支付FeeCode就是处方标识，诊间支付FeeCode就是his处方id
                    if (OutpatientTypeEnum.ON_LINE.getCode().equals(drugIOrdersVo.getOutpatientType())) {
                        odsOrderToPrescription.setFeeCode(odsOrderPrescriptionInfoVo.getPrescriptionInfoId());
                    } else {
                        odsOrderToPrescription.setFeeCode(odsOrderPrescriptionInfoVo.getPrescriptionId());
                    }
                    BigDecimal fee = feeMap.get(odsOrderPrescriptionInfoVo.getOrderPrescriptionInfoId());
                    odsOrderToPrescription.setTotalFee(fee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                odsOrderToPrescriptionDAO.save(odsOrderToPrescription);

                //保存处方订单明细
                OdsOrderPrescriptionInfo odsOrderPrescriptionInfo = new OdsOrderPrescriptionInfo();
                BeanUtils.copy(odsOrderPrescriptionInfoVo, odsOrderPrescriptionInfo);
                odsOrderPrescriptionInfo.setOrderId(odsPrescriptionOrder.getOrderId());
                odsOrderPrescriptionInfo.setOrderDetailId(odsOrderToPrescription.getOrderDetailId());
                odsOrderPrescriptionInfoDAO.save(odsOrderPrescriptionInfo);

                //保存处方订单药品明细
                for (OdsOrderPrescriptionDrug odsOrderPrescriptionDrug : odsOrderPrescriptionInfoVo.getOrderPrescriptionDrugList()) {
                    odsOrderPrescriptionDrugDAO.save(odsOrderPrescriptionDrug);
                }
            }
        }

        //保存处置信息
        if (CommonUtils.isNotEmpty(odsOrderExpenseRecords)) {
            for (OdsOrderExpenseRecordVo odsOrderExpenseRecordVo : odsOrderExpenseRecords) {
                odsOrderToPrescription = new OdsOrderToPrescription();
                odsOrderToPrescription.setExpressInfoId(odsExpressInfo.getExpressInfoId());
                //检验
                if (FeeTypeEnum.JIANYAN.getTitle().equals(odsOrderExpenseRecordVo.getBillCategoryCode())) {
                    odsOrderToPrescription.setFeeType(FeeTypeEnum.JIANYAN.getTitle());
                } else if (FeeTypeEnum.JIANCHA.getTitle().equals(odsOrderExpenseRecordVo.getBillCategoryCode())) {
                    //检查
                    odsOrderToPrescription.setFeeType(FeeTypeEnum.JIANCHA.getTitle());
                } else {
                    odsOrderToPrescription.setFeeType(FeeTypeEnum.QITA.getTitle());
                }
                List<OdsOrderExpenseDetail> disposalExpenseDetails = odsOrderExpenseRecordVo.getOrderExpenseDetailList();
                BigDecimal totalFee = new BigDecimal(0);
                if (CommonUtils.isNotEmpty(disposalExpenseDetails)) {
                    for (OdsOrderExpenseDetail disposalExpenseDetail : disposalExpenseDetails) {
                        if (null != disposalExpenseDetail) {
                            totalFee = totalFee.add(disposalExpenseDetail.getAmount().multiply(disposalExpenseDetail.getNumber()));
                        }
                    }
                }

                //云门诊
                if (OutpatientTypeEnum.ON_LINE.getCode().equals(drugIOrdersVo.getOutpatientType())) {
                    ConsultAsk consultAsk = consultAskServiceIntf.getConsultAsksByConsultId(odsOrderExpenseRecordVo.getConsultId());
                    odsOrderToPrescription.setConsultType(consultAsk.getConsultType());
                    odsOrderToPrescription.setConsultId(consultAsk.getConsultId());
                } else {
                    //诊间支付问诊类型写死
                    odsOrderToPrescription.setConsultType(ConsultTypeEnum.CLINIC.getTitle());
                    odsOrderToPrescription.setConsultId(drugIOrdersVo.getVisitId());
                }

                odsOrderToPrescription.setTotalFee(totalFee.doubleValue());
                odsOrderToPrescription.setOrderId(odsPrescriptionOrder.getOrderId());
                odsOrderToPrescription.setFeeCode(odsOrderExpenseRecordVo.getExpenseId());
                odsOrderToPrescriptionDAO.save(odsOrderToPrescription);

                //保存处置支付订单明细
                OdsOrderExpenseRecord odsOrderExpenseRecord = new OdsOrderExpenseRecord();
                BeanUtils.copy(odsOrderExpenseRecordVo, odsOrderExpenseRecord);
                odsOrderExpenseRecord.setOrderId(odsPrescriptionOrder.getOrderId());
                odsOrderExpenseRecord.setOrderDetailId(odsOrderToPrescription.getOrderDetailId());
                odsOrderExpenseRecordDAO.save(odsOrderExpenseRecord);

                //保存处置支付订单明细详情
                if (CommonUtils.isNotEmpty(odsOrderExpenseRecordVo.getOrderExpenseDetailList())) {
                    for (OdsOrderExpenseDetail odsOrderExpenseDetail : odsOrderExpenseRecordVo.getOrderExpenseDetailList()) {
                        odsOrderExpenseDetailDAO.save(odsOrderExpenseDetail);
                    }
                }

                orderTotalFee = orderTotalFee.add(totalFee);
            }
        }
        return orderTotalFee;
    }

    /*查询药店列表*/
    @Override
    public List<StoresInfo> findRecipeSuppliers(FindRecipeSuppliersRequestForEnd requestForEnd) throws ControllerException {

        Organization organization = organizationInfoService.getOrgDetailByOrgId(requestForEnd.getOrgId());
        if (null == organization) {
            throw new ControllerException("机构标识不能为空");
        }

        List<StoresInfo> storesInfoList = new ArrayList<>();
        String epitaxialOrganizationId = "";

        List<DrugInformation> drugInformations = new ArrayList<>();
        List<DrugInfoPro> drugInfoList = new ArrayList();
        PharmacyListReq pharmacyListReq = new PharmacyListReq();
        Set<String> orgSet = new HashSet<>();

        List<OdsPrescriptionInfo> odsPrescriptionInfos = prescriptionInfoIntf.queryByFeeNoList(requestForEnd.getFeeNoList());
        if (CommonUtils.isNotEmpty(odsPrescriptionInfos)) {
            if (odsPrescriptionInfos.size() != requestForEnd.getFeeNoList().size()) {
                throw new ControllerException("选择的单据数量与查询到的单据数量不一致，请刷新后重试");
            }

            for (OdsPrescriptionInfo odsPrescriptionInfo : odsPrescriptionInfos) {
                //外延机构
                if (CommonUtils.isNotEmpty(odsPrescriptionInfo.getEpitaxialOrganizationId())) {
                    epitaxialOrganizationId = odsPrescriptionInfo.getEpitaxialOrganizationId();
                    orgSet.add(epitaxialOrganizationId);
                } else {
                    orgSet.add(organization.getLocalOrgId());
                }

                if ("0".equals(odsPrescriptionInfo.getDeleteFlag()) && "1".equals(odsPrescriptionInfo.getAuditStatus())
                        && "2".equals(odsPrescriptionInfo.getOrderFlag()) && "0".equals(odsPrescriptionInfo.getPayStatus())) {
                    //查询处方明细
                    List<OdsPrescriptionDrug> odsPrescriptionDrugs = prescriptionInfoIntf.findByPrescriptionInfoId(odsPrescriptionInfo.getPrescriptionInfoId());
                    if (!CollectionUtils.isEmpty(odsPrescriptionDrugs)) {
                        for (OdsPrescriptionDrug odsPrescriptionDrug : odsPrescriptionDrugs) {
                            DrugInformation drugInformation = new DrugInformation();
                            drugInformations.add(drugInformation);
                            drugInformation.setDrugId(odsPrescriptionDrug.getOrgDrugId());
                            drugInformation.setDrugName(odsPrescriptionDrug.getOrgDrugName());
                            drugInformation.setFactoryId(odsPrescriptionDrug.getOrgFactoryId());
                            drugInformation.setFactoryName(odsPrescriptionDrug.getOrgFactoryName());
                            //因为处方类型和药品类型一致，直接set
                            drugInformation.setDrugType(Integer.valueOf(odsPrescriptionInfo.getPrescriptionType()));
                            //处方贴数不能为空、不能小于1
                            if (odsPrescriptionInfo.getNumberOfPackets() == null || odsPrescriptionInfo.getNumberOfPackets() < 1) {
                                odsPrescriptionInfo.setNumberOfPackets(1);
                            }
                            drugInformation.setSummation(odsPrescriptionDrug.getQuantity().multiply(BigDecimal.valueOf(odsPrescriptionInfo.getNumberOfPackets())));
                            DrugInfoPro drugInfo = new DrugInfoPro();
                            drugInfo.setDrugId(odsPrescriptionDrug.getOrgDrugId());
//                            drugInfo.setDoseUnit(odsPrescriptionDrug.getSpecification());
                            switch (odsPrescriptionInfo.getPrescriptionType()) {
                                case "1":
                                case "2":
                                    drugInfo.setDrugDemand(odsPrescriptionDrug.getQuantity().toString());
                                    pharmacyListReq.setTypeCode("21");//21西药
                                    break;
                                case "3":
                                    drugInfo.setMedicineCount(odsPrescriptionInfo.getNumberOfPackets());
                                    pharmacyListReq.setTypeCode("23");//23中草药
                                    break;
                            }
                            drugInfoList.add(drugInfo);
                        }
                    }
                } else {
                    throw new ControllerException("单据发生变更，请刷新后重试");
                }
            }

            if (orgSet.size() >= 2) {
                throw new ControllerException("外延处方和非外延处方不能一起支付");
            }
        } else {
            //通过就诊序号查询his开具的所有处方，通过feeNoList过滤出本次要支付的处方数据
            DrugIOrdersQo drugIOrdersQo = new DrugIOrdersQo();
            drugIOrdersQo.setVisitIdList(requestForEnd.getVisitIdList());
            drugIOrdersQo.setPrescriptionIdList(requestForEnd.getFeeNoList());
            drugIOrdersQo.setOrgId(requestForEnd.getOrgId());
            drugIOrdersQo.setOutpatientType(requestForEnd.getOutpatientType());

            //订单处方明细集合
            //获取订单处方明细集合
            List<OdsOrderPrescriptionInfoVo> odsOrderPrescriptionInfoList = queryOrderPrescriptionInfoList(drugIOrdersQo);

            for (OdsOrderPrescriptionInfoVo odsOrderPrescriptionInfoVo : odsOrderPrescriptionInfoList) {
                for (OdsOrderPrescriptionDrug odsOrderPrescriptionDrug : odsOrderPrescriptionInfoVo.getOrderPrescriptionDrugList()) {
                    DrugInformation drugInformation = new DrugInformation();
                    drugInformations.add(drugInformation);
                    drugInformation.setDrugId(odsOrderPrescriptionDrug.getOrgDrugId());
                    drugInformation.setDrugName(odsOrderPrescriptionDrug.getOrgDrugName());
                    drugInformation.setFactoryId(odsOrderPrescriptionDrug.getOrgFactoryId());
                    drugInformation.setFactoryName(odsOrderPrescriptionDrug.getOrgFactoryName());
                    //因为处方类型和药品类型一致，直接set
                    drugInformation.setDrugType(Integer.valueOf(odsOrderPrescriptionInfoVo.getPrescriptionType()));
                    //处方贴数不能为空、不能小于1
                    if (odsOrderPrescriptionInfoVo.getNumberOfPackets() == null || odsOrderPrescriptionInfoVo.getNumberOfPackets() < 1) {
                        odsOrderPrescriptionInfoVo.setNumberOfPackets(1);
                    }
                    drugInformation.setSummation(odsOrderPrescriptionDrug.getQuantity().multiply(BigDecimal.valueOf(odsOrderPrescriptionInfoVo.getNumberOfPackets())));
                    DrugInfoPro drugInfo = new DrugInfoPro();
                    drugInfo.setDrugId(odsOrderPrescriptionDrug.getOrgDrugId());
                    drugInfo.setDoseUnit(odsOrderPrescriptionDrug.getSpecification());
                    if ("1".equals(odsOrderPrescriptionInfoVo.getPrescriptionType())) {//非西药方
                        drugInfo.setDrugDemand(odsOrderPrescriptionDrug.getQuantity().toString());
                        pharmacyListReq.setTypeCode("21");//21西药
                    } else {
                        drugInfo.setMedicineCount(odsOrderPrescriptionInfoVo.getNumberOfPackets());
                        pharmacyListReq.setTypeCode("23");//23中草药
                    }
                    drugInfoList.add(drugInfo);
                }
            }
        }

        if (CommonUtils.isNotEmpty(drugInformations)) {
            try {
                FindRecipeSuppliersRequestBean request = new FindRecipeSuppliersRequestBean();

                request.setOrganizationId(organization.getLocalOrgId());
                request.setHisUrl(organization.getProHisUrl());
                request.setDrugList(drugInformations);
                List<StoresInfo> tempStoresList = new ArrayList<>();

                FindRecipeSuppliersXMLReq findRecipeSuppliersXMLReq = new FindRecipeSuppliersXMLReq();
                findRecipeSuppliersXMLReq.setVisitOrganization(request.getOrganizationId());
                List<FindRecipeSuppliersXMLReq.Drug> drugLists = new ArrayList<>();
                FindRecipeSuppliersXMLReq.Drug drug = null;

                if (CommonUtils.isNotEmpty(drugInformations)) {
                    for (DrugInformation drugInformation : drugInformations) {
                        drug = new FindRecipeSuppliersXMLReq.Drug();
                        drug.setDrugName(drugInformation.getDrugName());
                        drug.setDrugProductionPlace(drugInformation.getFactoryName());
                        drug.setDrugProductionPlaceId(drugInformation.getFactoryId());
                        drug.setDrugSendNumber(drugInformation.getSummation().toString());
                        drug.setDrugsNumber(drugInformation.getDrugId());
                        drug.setDrugType(drugInformation.getDrugType().toString());
                        drugLists.add(drug);
                    }
                }

                findRecipeSuppliersXMLReq.setDrugLists(drugLists);

                BasePropertyConfig propertyCode = serviceOpenService.getBasePropertyConfig("013708", organization.getOrgId());
                if (null != propertyCode && "1".equals(propertyCode.getPropertyData())) {
                    FindRecipeSuppliersXMLResp findRecipeSuppliersXML = diagnosisPayTradeService.findRecipeSuppliersXML(findRecipeSuppliersXMLReq);
                    if (CommonUtils.isNotEmpty(findRecipeSuppliersXML)) {
                        List<FindRecipeSuppliersXMLResp.Stores> storesList = findRecipeSuppliersXML.getStoresList();
                        StoresInfo storesInfo = null;
                        if (CommonUtils.isNotEmpty(storesList)) {
                            for (FindRecipeSuppliersXMLResp.Stores stores : storesList) {
                                storesInfo = new StoresInfo();
                                storesInfo.setStoreCode(stores.getPharmacyId());
                                storesInfo.setStoreName(stores.getPharmacyName());
                                storesInfo.setPhone(stores.getPharmacyPhone());
                                storesInfo.setAddress(stores.getPharmacyAddress());
                                storesInfo.setTotalPrice(stores.getTotalCost());
                                storesInfo.setStoreType("1");

                                Position position = new Position();
                                position.setLatitude(stores.getLatitude());
                                position.setLongitude(stores.getLongitude());
                                storesInfo.setPosition(position);

                                tempStoresList.add(storesInfo);
                            }
                        }
                    }
                } else {
                    tempStoresList = diagnosisPayTradeService.findRecipeSuppliers(request);
                }

                storesInfoList.addAll(tempStoresList);
            } catch (Throwable throwable) {
                logger.error("院内药房列表失败:" + throwable.getMessage());
            }


            String propertyCode;
            if ("1".equals(requestForEnd.getOutpatientType())) {
                //诊间支付是否开通流转
                propertyCode = "013602";
            } else {
                //云支付是否开通流转
                propertyCode = "013604";
            }

            //获取是否开通处方流转的系统参数
            int operationPlatformFlag = 0;
            BasePropertyConfig basePropertyConfig = serviceOpenService.getBasePropertyConfig(propertyCode, requestForEnd.getOrgId());
            if (basePropertyConfig != null) {
                operationPlatformFlag = Integer.parseInt(basePropertyConfig.getPropertyData());
            }

            //开通了流转，查询处方流转平台的药店列表-项目上对接的处方流转平台可能不相同，根据具体情况再调整出入参
            if (1 == operationPlatformFlag) {
                //通过系统参数判断是否开通处方流转
                pharmacyListReq.setLatitude(requestForEnd.getLatitude());
                pharmacyListReq.setLongitude(requestForEnd.getLongitude());
                List<DrugInfoForOrg> drugInfo = new ArrayList<>();
                DrugInfoForOrg drugInfoForOrg = new DrugInfoForOrg();

                if (orgSet.size() > 0) {
                    for (String s : orgSet) {
                        epitaxialOrganizationId = s;
                    }
                    drugInfoForOrg.setHospitalIdOutter(epitaxialOrganizationId);//外部机构id
                } else {
                    drugInfoForOrg.setHospitalIdOutter(organization.getLocalOrgId());
                }

                drugInfoForOrg.setDetailInfo(drugInfoList);
                drugInfo.add(drugInfoForOrg);
                pharmacyListReq.setDrugInfo(drugInfo);
                String param = JSON.toJSON(pharmacyListReq).toString();
                List<PharmacyListResp> pharmacyListRespList = new ArrayList<>();
                StoresInfo storesInfo;
                //药店药品列表
                List<StoresInfo.PrescriptionInfo> storeDrugInfos;
                //药店药品
                StoresInfo.PrescriptionInfo storeDrugInfo;
                try {
                    String result = OperationPlatformSignUtil.signPost(param, OperationPlatformSignUtil.PHARMACY_LIST);
                    JSONObject resultJson = JSONObject.parseObject(result);
                    if (ResultCode.SUCCESS == resultJson.getIntValue("code")) {
                        pharmacyListRespList = JSONObject.parseArray(resultJson.getJSONArray("body").toJSONString(), PharmacyListResp.class);
                        if (!CollectionUtils.isEmpty(pharmacyListRespList)) {
                            for (PharmacyListResp pharmacyListResp : pharmacyListRespList) {
                                storesInfo = new StoresInfo();
                                storesInfo.setStoreType("2");//院外药房
                                storesInfo.setAddress(pharmacyListResp.getOrgAddress());
                                storesInfo.setPhone(pharmacyListResp.getPhone());
                                storesInfo.setStoreCode(pharmacyListResp.getStoreId());
                                storesInfo.setOperatePlatformStoreId(pharmacyListResp.getOperatePlatformStoreId());//运营平台药店id
                                storesInfo.setStoreName(pharmacyListResp.getStoreName());
                                storesInfo.setDistance(pharmacyListResp.getDistance());
                                //代煎费
                                storesInfo.setBoilFeeAmount(pharmacyListResp.getDecoctingFee());
                                //药店的代煎包配置
                                storesInfo.setDrugCapacities(pharmacyListResp.getDrugCapacities());
                                //是否支持代煎
                                storesInfo.setDecoctingFlag(pharmacyListResp.getDecoctingFlag());
                                Position position = new Position();
                                position.setLatitude(pharmacyListResp.getLatitude());
                                position.setLongitude(pharmacyListResp.getLongitude());
                                storesInfo.setPosition(position);
                                BigDecimal totalPrice = new BigDecimal(0.0);
                                List<PrescriptionInfo> pharmacyListRespDrugInfo = pharmacyListResp.getDrugInfo();
                                //计算总金额，药店药品赋值
                                if (!CollectionUtils.isEmpty(pharmacyListRespDrugInfo)) {
                                    storeDrugInfos = new ArrayList<>();
                                    for (PrescriptionInfo prescriptionInfo : pharmacyListRespDrugInfo) {
                                        totalPrice = totalPrice.add(new BigDecimal(prescriptionInfo.getAmount()));

                                        storeDrugInfo = new StoresInfo.PrescriptionInfo();
                                        BeanUtils.copy(prescriptionInfo, storeDrugInfo);
                                        storeDrugInfos.add(storeDrugInfo);
                                    }
                                    storesInfo.setDrugInfo(storeDrugInfos);
                                }
                                storesInfo.setTotalPrice(totalPrice.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                                storesInfoList.add(storesInfo);
                            }
                        }
                    } else {
                        logger.error("院外药房列表失败:" + resultJson.getString("msg"));
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            throw new ControllerException("单据不存在，请刷新后重试");
        }
        return storesInfoList;
    }

    /**
     * 对APP的状态是（实际上的订单状态+实际上支付状态）组合而成，"orderStatus": 0,//订单状态 0 待付款 ；1 待发货 ； 2 待收货  ； 3 支付超时  ；4 已取消 ; 5 已收货
     * 实际上的订单状态  1 待发货 ； 2 待收货  ；3已收货'
     * 实际上支付状态   0：待支付   1：已支付   2：支付超时   3 已取消
     * 取消订单
     *
     * @param orderId
     */
    @Override
    @RpcService
    public Boolean cancelOrder(String orderId) throws ControllerException {
//        BaseResponse baseResponse = new BaseResponse<>();
        OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.get(orderId);
        if (null == odsPrescriptionOrder) {
            throw new ControllerException("该订单不存在");
        }
        //院内的已支付订单不允许取消
        if ("1".equals(odsPrescriptionOrder.getPayStatus()) && CommonUtils.isEmpty(odsPrescriptionOrder.getPlatformOrderId())) {
            throw new ControllerException("该订单已支付，不允许取消订单");
        }
        if ("2".equals(odsPrescriptionOrder.getOrderStatus())) {
            throw new ControllerException("该订单已发货，不允许取消订单");
        }
        if ("3".equals(odsPrescriptionOrder.getOrderStatus())) {
            throw new ControllerException("该订单已确认收货，不允许取消订单");
        }
        //去处方流转平台取消订单
        if (!StringUtils.isEmpty(odsPrescriptionOrder.getPlatformOrderId())) {//有流转的才去运营平台取消订单
            BaseResponse baseResponse = this.cancelPrescriptionOrder(odsPrescriptionOrder.getPlatformOrderId(), odsPrescriptionOrder.getOrderId());
            if (baseResponse.getCode() != ResultCode.SUCCESS) {
                throw new ControllerException(baseResponse.getMessage());
//                return baseResponse;//取消失败直接返回。
            }
        }
        //支付成功的才退款
        if ("1".equals(odsPrescriptionOrder.getPayStatus())) {
            PayTrade payTrade = payTradeService.getPayTrade(odsPrescriptionOrder.getTradeNo());
            if (null != payTrade) {
                try {
                    payTradeService.refundByTradeType(orderId, payTrade.getTradeType());
                } catch (Throwable throwable) {
                    throw new ControllerException("退款失败，取消订单失败");
                }
            }
        }
        //修改订单状态
        odsPrescriptionOrder.setPayStatus("3");
        odsPrescriptionOrderDAO.update(odsPrescriptionOrder);
        List<OdsOrderToPrescription> odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderToPrescriptionBy(odsPrescriptionOrder.getOrderId());
        if (CommonUtils.isNotEmpty(odsOrderToPrescriptions)) {
            for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
                if (FeeTypeEnum.XIYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CHENGYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CAOYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) {

                    OdsPrescriptionInfo odsPrescriptionInfo = prescriptionInfoIntf.getOdsPrescriptionInfo(odsOrderToPrescription.getFeeCode());
                    if (null != odsPrescriptionInfo && odsPrescriptionInfo.getExpirationDate() != null && odsPrescriptionInfo.getExpirationDate().getTime() > System.currentTimeMillis()) {
                        odsPrescriptionInfo.setOrderFlag("2");
                        odsPrescriptionInfo.setPayStatus("0");
                        prescriptionInfoIntf.updateOdsPrescriptionInfo(odsPrescriptionInfo);
                        ConsultAsk consultAsk = consultAskServiceIntf.getConsultAsksByConsultId(odsPrescriptionInfo.getConsultId());
                        consultAsk.setPrescriptionStatus(1);
                        consultAskServiceIntf.updateConsultAsk(consultAsk);
                    }
                }
            }
        }
        return true;
    }

    /**
     * 对APP的状态是（实际上的订单状态+实际上支付状态）组合而成，"orderStatus": 0,//订单状态 0 待付款 ；1 待发货 ； 2 待收货  ； 3 支付超时  ；4 已取消 ; 5 已收货
     * 实际上的订单状态  1 待发货 ； 2 待收货  ；3已收货'
     * 实际上支付状态   0：待支付   1：已支付   2：支付超时   3 已取消
     * 删除订单
     */
    @Override
    @RpcService
    public void deleteDrugOrder(DeleteDrugOrderQo qo) throws ControllerException {
        if (CommonUtils.isEmpty(qo.getOrderId())) {
            throw new ControllerException("订单id不能为空");
        }
        OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.get(qo.getOrderId());

        if (null == odsPrescriptionOrder) {
            throw new ControllerException("该订单不存在");
        }

        //只有支付超时、已取消、已收货才能删除订单
        if ("2".equals(odsPrescriptionOrder.getPayStatus()) || "3".equals(odsPrescriptionOrder.getPayStatus()) || "3".equals(odsPrescriptionOrder.getOrderStatus())) {
            odsPrescriptionOrder.setDeleteFlag("1");
            odsPrescriptionOrder.setDeleteDt(new Date());
            UserVo userVo = null;
            try {
                userVo = baseUserManageUnitService.getUserIdByOnline();
            } catch (Exception e) {
                logger.info("获取登录用户失败");
            }
            odsPrescriptionOrder.setDeleteUser(userVo.getUserId());
            odsPrescriptionOrderDAO.update(odsPrescriptionOrder);
        } else {
            throw new ControllerException("该订单正在进行中，无法删除");
        }
    }


    /**
     * 对APP的状态是（实际上的订单状态+实际上支付状态）组合而成，"orderStatus": 0,//订单状态 0 待付款 ；1 待发货 ； 2 待收货  ； 3 支付超时  ；4 已取消 ; 5 已收货
     * 实际上的订单状态orderStatus  1 待发货 ； 2 待收货  ；3已收货'
     * 实际上支付状态payStatus   0：待支付   1：已支付   2：支付超时   3 已取消
     * 确认收货
     *
     * @param orderId
     */
    @Override
    @RpcService
    public void applyOrder(String orderId) throws ControllerException {
        OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.get(orderId);

        if (null == odsPrescriptionOrder) {
            throw new ControllerException("该订单不存在");
        }
        //标记为已收货
        odsPrescriptionOrder.setOrderStatus("3");
        odsPrescriptionOrderDAO.update(odsPrescriptionOrder);

        //发货订单表
        OdsExpressInfo odsExpressInfo = odsExpressInfoDAO.getOdsExpressInfo(orderId);
        if (null != odsExpressInfo) {
            //确认收货
//            odsExpressInfo.setConfirmReceipt("1");
            odsExpressInfo.setConfirmReceiptTime(new Date());
            odsExpressInfoDAO.update(odsExpressInfo);
        }
        ExpressOrder expressOrder = expreeOrderDAO.getByOrderId(orderId);
        if (null != odsExpressInfo) {
            expressOrder.setConfirmReceipt("1");
            expressOrder.setCreateTime(new Date());
            expreeOrderDAO.update(expressOrder);

            expreeOrderDetailDAO.updateDetailByExpressId(expressOrder.getExpressId());
        }
    }

    /**
     * 预结算
     *
     * @return
     */
    @Override
    @RpcService
    public Map<String, Object> payBudget(Map<String, Object> request) {
        Map<String, Object> map = new HashMap<>();
        map.put("fee", "0.01");
        map.put("budgetNumber", DateUtils.getTimeStep(new Date()));
        map.put("totalFee", "0.01");
        return map;
    }


    /**
     * 获得订单id
     *
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString();
    }


    /**
     * 获取取货地址
     *
     * @return
     */
    @Override
    @RpcService
    public GetExecuteAddressVo getExecuteAddress(GetExecuteAddressQo qo) throws ControllerException {
        GetExecuteAddressVo addressVo = new GetExecuteAddressVo();
        Map<String, Object> organization = organizationInfoService.getOrgMainDetailById(qo.getOrgId());
        if (CommonUtils.isNotEmpty(organization)) {
            addressVo.setOrgId((String) organization.get("orgId"));
            addressVo.setOrgName((String) organization.get("fullName"));
            addressVo.setAddress((String) organization.get("address"));
            addressVo.setLongitude((String) organization.get("longitude"));
            addressVo.setLatitude((String) organization.get("latitude"));
            addressVo.setContactNo((String) organization.get("consultNo"));
        }

        String orderId = qo.getOrderId();

        if (CommonUtils.isEmpty(orderId) && CommonUtils.isNotEmpty(qo.getTradeNo())) {
            OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.getOdsPrescriptionOrder(qo.getTradeNo());
            if (CommonUtils.isNotEmpty(odsPrescriptionOrder)) {
                orderId = odsPrescriptionOrder.getOrderId();
            }
        }

        if (CommonUtils.isNotEmpty(orderId)) {
            OdsExpressInfo odsExpressInfo = odsExpressInfoDAO.getOdsExpressInfo(qo.getOrderId());
            if (odsExpressInfo != null) {
                addressVo.setExecuteAddress(odsExpressInfo.getExecuteAddress());
            }
        }

        return addressVo;
    }

    /**
     * @description: 获取处方支付预结算
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/1/2 15:08
     */
    @RpcService
    @Override
    public NewGetPrecalculatedFeeVO getDrugOrderPrecalculatedFee(GetDrugOrderPrecalculatedFeeQo qo) throws ControllerException {
        PrecalculatedFeeRequestBean precalculatedFeeRequestBean = new PrecalculatedFeeRequestBean();
        NewGetPrecalculatedFeeRequestBean.FeeRecordsBean requestFeeRecord = null;

        NewGetPrecalculatedFeeVO drugOrderPrecalculatedFeeVO = new NewGetPrecalculatedFeeVO();
        try {
            if (CommonUtils.isEmpty(qo.getOrderId())) {
                throw new ControllerException("订单不能为空");
            }
            precalculatedFeeRequestBean.setOrderId(qo.getOrderId());

            OdsPrescriptionOrder odsPrescriptionOrder = odsPrescriptionOrderDAO.get(qo.getOrderId());
            if (CommonUtils.isEmpty(odsPrescriptionOrder)) {
                throw new ControllerException("该订单不存在");
            }

            //"013705" text="复诊处方数据对接方式(0:json 1:xml),默认:0"
            BasePropertyConfig propertyCode = serviceOpenService.getBasePropertyConfig("013705", odsPrescriptionOrder.getOrgId());

            if (null != propertyCode && "1".equals(propertyCode.getPropertyData())) {
                List<OdsOrderToPrescription> odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderToPrescriptionBy(qo.getOrderId());
                if (CommonUtils.isNotEmpty(odsOrderToPrescriptions)) {
                    String consultId = "";

                    //处方id集合
                    List<String> prescribeIdList = new ArrayList<>();
                    //检验检查申请单id集合
                    List<String> expenseIdList = new ArrayList<>();

                    //代煎费
                    BigDecimal decoctingFee = new BigDecimal(0);
                    //快递费
                    BigDecimal expressFee = new BigDecimal(0);

                    for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {

                        if (CommonUtils.isEmpty(consultId) && CommonUtils.isNotEmpty(odsOrderToPrescription.getConsultId())) {
                            consultId = odsOrderToPrescription.getConsultId();
                        }

                        if (FeeTypeEnum.XIYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CHENGYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CAOYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                            //获取处方id集合
                            prescribeIdList.add(odsOrderToPrescription.getFeeCode());//处方id
                        } else if (!FeeTypeEnum.DJF.getTitle().equals(odsOrderToPrescription.getFeeType()) && !FeeTypeEnum.KDF.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                            //获取医技id集合
                            expenseIdList.add(odsOrderToPrescription.getFeeCode());//获取医技id集合
                        }

                        //代煎费
                        if (FeeTypeEnum.DJF.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                            decoctingFee = new BigDecimal(odsOrderToPrescription.getTotalFee());
                        }

                        //快递费
                        if (FeeTypeEnum.KDF.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                            expressFee = new BigDecimal(odsOrderToPrescription.getTotalFee());
                        }

                        //就诊序号赋值
                        if(CommonUtils.isNotEmpty(odsOrderToPrescription.getConsultId())){
                            //门诊缴费类型的直接取值，其他问诊类型的从问诊记录取
                            if(ConsultTypeEnum.CLINIC.getTitle().equals(odsOrderToPrescription.getConsultType())){
                                precalculatedFeeRequestBean.setVisitId(odsOrderToPrescription.getConsultId());
                            }else {
                                ConsultAsk consultAsk = consultAskServiceIntf.getConsultAskByConsultId(odsOrderToPrescription.getConsultId());
                                if(null != consultAsk){
                                    precalculatedFeeRequestBean.setVisitId(consultAsk.getVisitNo());
                                }
                            }
                        }
                    }

                    //保存处方费用
                    setConfirmDrugXmlRequest(precalculatedFeeRequestBean, prescribeIdList);
                    //保存检验、检查费用
                    setConfirmExpenseXmlRequest(precalculatedFeeRequestBean, expenseIdList);

                    Organization organization = organizationInfoService.getOrgDetailByOrgId(odsPrescriptionOrder.getOrgId());
                    if (null != organization) {
                        Set<Card> cards = hcnMpiProvider.getCards(odsPrescriptionOrder.getMpiId());
                        String patientId = null;
                        if(CommonUtils.isNotEmpty(cards)){
                            List<Card> collect = cards.stream().filter(card -> card.getSource().equals(organization.getOrgId()) && CommonUtils.isNotEmpty(card.getPatientCode())).collect(Collectors.toList());
                            if(CommonUtils.isNotEmpty(collect)){
                                patientId = collect.get(0).getPatientCode();
                            }
                        }
                        if(null == patientId){
                            throw new ControllerException("该居民未绑定医院" + organization.getFullName() + "档案标识");
                        }

                        precalculatedFeeRequestBean.setPatientCode(patientId);
                    }

                    if (CommonUtils.isNotEmpty(odsPrescriptionOrder.getVoucherId())) {
                        String[] voucherIds = odsPrescriptionOrder.getVoucherId().split("\\,");
                        if (CommonUtils.isNotEmpty(voucherIds)) {
                            List<String> voucherIdList = new ArrayList<>();
                            for (String voucherId : voucherIds) {
                                voucherIdList.add(voucherId);
                            }
                            precalculatedFeeRequestBean.setVoucherIdList(voucherIdList);
                        }
                    }

                    precalculatedFeeRequestBean.setHospitalCode(organization.getLocalOrgId());
                    BaseResponse<NewGetPrecalculatedFeeResponseBean> response = null;
                    try {
                        logger.info("request=" + JSONUtils.writeValueAsString(precalculatedFeeRequestBean));

                        Map<String, String> baseDicMap = new HashMap<>();
                        List<QueryDicContrastListVo> queryDicContrastListVos = dicContrastService.queryDicContrastList("fee_type", organization.getOrgId());
                        if (CommonUtils.isNotEmpty(queryDicContrastListVos)) {
                            for (QueryDicContrastListVo queryDicContrastListVo : queryDicContrastListVos) {
                                baseDicMap.put(queryDicContrastListVo.getBaseItemCode(), queryDicContrastListVo.getHisItemCode());
                            }
                        }
                        for (NewGetPrecalculatedFeeRequestBean.FeeRecordsBean feeRecordsBean : precalculatedFeeRequestBean.getFeeRecords()) {
                            if (baseDicMap.keySet().contains(feeRecordsBean.getFeeTypeCode())) {
                                feeRecordsBean.setFeeTypeCode(baseDicMap.get(feeRecordsBean.getFeeTypeCode()));
                            }
                        }

                        response = diagnosisPayTradeService.getPrecalculatedFeeXML(precalculatedFeeRequestBean);
                    } catch (ControllerException e) {
                        logger.error("error", e);
                        throw e;
                    } catch (Throwable throwable) {
                        logger.error("error", throwable);
                        throw new ControllerException(CodeDefinition.CANNOT_GET_PRECALCULATE_FEE_RECORDS, "预结算失败");
                    }
                    if (response.getCode() == 200) {
                        NewGetPrecalculatedFeeResponseBean newGetPrecalculatedFeeResponseBean = JSONObject.parseObject(JSONArray.toJSONString(response.getData()), NewGetPrecalculatedFeeResponseBean.class);
                        drugOrderPrecalculatedFeeVO.setOrgId(odsPrescriptionOrder.getOrgId());
                        drugOrderPrecalculatedFeeVO.setTotalFee(newGetPrecalculatedFeeResponseBean.getTotalFee());
                        drugOrderPrecalculatedFeeVO.setAmount(newGetPrecalculatedFeeResponseBean.getTotalFee());
                        drugOrderPrecalculatedFeeVO.setPayAmount(newGetPrecalculatedFeeResponseBean.getTotalFee());
                        drugOrderPrecalculatedFeeVO.setDeductionAmount(newGetPrecalculatedFeeResponseBean.getDeductionAmount());

                        if (CommonUtils.isNotEmpty(odsOrderToPrescriptions)) {
                            List<NewGetPrecalculatedFeeVO.FeeRecord> feeRecords = new ArrayList<>();
                            NewGetPrecalculatedFeeVO.FeeRecord feeRecord;
                            for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
                                feeRecord = new NewGetPrecalculatedFeeVO.FeeRecord();
                                feeRecord.setFeeNo(odsOrderToPrescription.getFeeCode());
                                feeRecord.setFeeTypeCode(odsOrderToPrescription.getFeeType());
                                feeRecords.add(feeRecord);
                            }
                            drugOrderPrecalculatedFeeVO.setFeeRecords(feeRecords);
                        }

                        BigDecimal totalFee = new BigDecimal(newGetPrecalculatedFeeResponseBean.getTotalFee()).add(decoctingFee).add(expressFee);
                        BigDecimal amount = new BigDecimal(newGetPrecalculatedFeeResponseBean.getAmount()).add(decoctingFee).add(expressFee);
                        BigDecimal payAmount = new BigDecimal(newGetPrecalculatedFeeResponseBean.getPayAmount()).add(decoctingFee).add(expressFee);

                        drugOrderPrecalculatedFeeVO.setTotalFee(totalFee.setScale(2, RoundingMode.HALF_UP).doubleValue());
                        drugOrderPrecalculatedFeeVO.setAmount(amount.setScale(2, RoundingMode.HALF_UP).doubleValue());
                        drugOrderPrecalculatedFeeVO.setPayAmount(payAmount.setScale(2, RoundingMode.HALF_UP).doubleValue());
                        drugOrderPrecalculatedFeeVO.setPaymentBudgetNumber(newGetPrecalculatedFeeResponseBean.getPaymentBudgetNumber());
                        drugOrderPrecalculatedFeeVO.setInvoiceNumber(newGetPrecalculatedFeeResponseBean.getInvoiceNumber());
                        return drugOrderPrecalculatedFeeVO;
                    } else {
                        throw new ControllerException(CodeDefinition.CANNOT_GET_PRECALCULATE_FEE_RECORDS, "HIS预结算失败:" + response.getMessage());
                    }
                }
            } else {
//                //TODO 预结算金额写死0.01
//                odsPrescriptionOrder.setTotalFee(0.01);
//
//                drugOrderPrecalculatedFeeVO.setOrgId(odsPrescriptionOrder.getOrgId());
//                drugOrderPrecalculatedFeeVO.setTotalFee(odsPrescriptionOrder.getTotalFee());
//                drugOrderPrecalculatedFeeVO.setAmount(odsPrescriptionOrder.getTotalFee());
//                drugOrderPrecalculatedFeeVO.setPayAmount(odsPrescriptionOrder.getTotalFee());
//
//                List<OdsOrderToPrescription> odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderToPrescriptionBy(qo.getOrderId());
//                if (CommonUtils.isNotEmpty(odsOrderToPrescriptions)) {
//                    List<NewGetPrecalculatedFeeVO.FeeRecord> feeRecords = new ArrayList<>();
//                    NewGetPrecalculatedFeeVO.FeeRecord feeRecord;
//                    for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
//                        feeRecord = new NewGetPrecalculatedFeeVO.FeeRecord();
//                        feeRecord.setFeeNo(odsOrderToPrescription.getFeeCode());
//                        feeRecord.setFeeTypeCode(odsOrderToPrescription.getFeeType());
//                        feeRecords.add(feeRecord);
//                    }
//                    drugOrderPrecalculatedFeeVO.setFeeRecords(feeRecords);
//                }
//                return drugOrderPrecalculatedFeeVO;
            }
            return drugOrderPrecalculatedFeeVO;
        } catch (ControllerException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ControllerException("获取预结算失败");
        }
    }


    /**
     * @Author:FangZhiyi
     * @Description 处方流转平台订单状态更新通知
     * @Params [recipeStatusNoticeReq]
     * @Return com.bsoft.hessian.entity.BaseResponse
     * @Data Created in 2020/9/5 21:08
     * @Moddified By:
     */
    @Override
    public BaseResponse recipeStatusNotice(RecipeStatusNoticeReq recipeStatusNoticeReq) {
        OdsPrescriptionOrder order = odsPrescriptionOrderDAO.getOrderByOrderNo(recipeStatusNoticeReq.getOrderNo());
        if (order == null) {
            return BaseRespUtil.setResultError("不存在订单ID为：" + recipeStatusNoticeReq.getOrderNo() + "的健康通订单，请查证");
        }
        switch (recipeStatusNoticeReq.getNoticeType()) {
            //药店发货
            case "01":
                //更新物流
            case "04":
                order.setOrderStatus("2");
                DistributionInfo delivery = recipeStatusNoticeReq.getDelivery();
                if (delivery != null) {
                    order.setExpressCode(delivery.getTransportCode());
                }
                odsPrescriptionOrderDAO.update(order);
                OdsExpressInfo odsExpressInfo = odsExpressInfoDAO.getOdsExpressInfo(order.getOrderId());
                if (odsExpressInfo != null) {
                    odsExpressInfo.setDeliveryTime(new Date());
                    odsExpressInfoDAO.update(odsExpressInfo);
                }
                ExpressOrder orderDetail = expreeOrderDAO.getByOrderId(order.getOrderId());
                if (null == orderDetail) {
                    orderDetail = new ExpressOrder();
                    orderDetail.setExpressId(UUID.randomUUID().toString().replace("-", ""));
                    orderDetail.setOrderId(order.getOrderId());
                    orderDetail.setExpressCode(delivery.getTransportCode());
                    orderDetail.setExpressOrderId(delivery.getDeliveryNo());
                    orderDetail.setCreateTime(new Date());
                    orderDetail.setDeleteFlag("0");
                    expreeOrderDAO.save(orderDetail);
                } else {
                    orderDetail.setExpressCode(delivery.getTransportCode());
                    orderDetail.setExpressOrderId(delivery.getDeliveryNo());
                    expreeOrderDAO.update(orderDetail);
                }
                break;
            //取消订单
            case "02":
//                order.setDeleteFlag("1");
//                order.setDeleteDt(new Date());
//                order.setDeleteUser("运营平台");
//                odsPrescriptionOrderDAO.update(order);
                try {
                    this.cancelOrder(order.getOrderId());
                } catch (ControllerException e) {
                    e.printStackTrace();
                }
                break;
            //订单完成 - 核销、收款
            case "03":
                order.setOrderStatus("3");
                odsPrescriptionOrderDAO.update(order);

                OdsExpressInfo info = odsExpressInfoDAO.getOdsExpressInfo(order.getOrderId());
                if (info != null) {
                    info.setConfirmReceipt((byte) 1);
                    info.setConfirmReceiptTime(new Date());
                    odsExpressInfoDAO.update(info);
                }

                ExpressOrder detail = expreeOrderDAO.getByOrderId(order.getOrderId());
                if (null == detail) {
                    detail = new ExpressOrder();
                    detail.setExpressId(UUID.randomUUID().toString().replace("-", ""));
                    detail.setOrderId(order.getOrderId());
                    detail.setCreateTime(new Date());
                    detail.setConfirmReceipt("1");
                    detail.setConfirmReceiptTime(new Date());
                    detail.setDeleteFlag("0");
                    expreeOrderDAO.save(detail);
                } else {
                    detail.setConfirmReceipt("1");
                    detail.setConfirmReceiptTime(new Date());
                    expreeOrderDAO.update(detail);
                }
                break;
            //部分退款
            case "05":
                order.setOrderStatus("4");
                odsPrescriptionOrderDAO.update(order);
                break;
            default:
                break;
        }
        return BaseRespUtil.setResultSuccess();
    }

    /**
     * @description: 设置请求入参
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/10/31 11:37
     * @param: request
     * @param: consultId
     * @param: payTrade
     * @param: odsPrescriptionOrder
     * @param: odsExpressInfo
     * @param: prescribeIdList
     * @return: void
     */
    public void setConfirmDrugXmlRequest(PrecalculatedFeeRequestBean request, List<String> prescribeIdList) throws ControllerException {
        //保存处方信息
        if (CommonUtils.isNotEmpty(prescribeIdList)) {
            //his费用列表
            List<NewGetPrecalculatedFeeRequestBean.FeeRecordsBean> feeRecords = new ArrayList<>();
            //his费用对象
            NewGetPrecalculatedFeeRequestBean.FeeRecordsBean feeRecord;

            //线上处方列表
            List<OdsOrderPrescriptionInfo> orderPrescriptionInfoList = odsOrderPrescriptionInfoDAO.findByOrderId(request.getOrderId());

            if (CommonUtils.isNotEmpty(orderPrescriptionInfoList)) {
                for (OdsOrderPrescriptionInfo odsOrderPrescriptionInfo : orderPrescriptionInfoList) {
                    feeRecord = new NewGetPrecalculatedFeeRequestBean.FeeRecordsBean();
                    feeRecord.setFeeNo(odsOrderPrescriptionInfo.getPrescriptionId());

                    String feeType = "";
                    String feeTypeName = "";
                    if (DrugTypeEnum.XIYAO.getCode().equals(odsOrderPrescriptionInfo.getPrescriptionType())) {
                        feeType = FeeTypeEnum.XIYAO.getTitle();
                        feeTypeName = FeeTypeEnum.XIYAO.getContext();
                    } else if (DrugTypeEnum.ZHONGYAO.getCode().equals(odsOrderPrescriptionInfo.getPrescriptionType())) {
                        feeType = FeeTypeEnum.CHENGYAO.getTitle();
                        feeTypeName = FeeTypeEnum.CHENGYAO.getContext();
                    } else if (DrugTypeEnum.CAOYAO.getCode().equals(odsOrderPrescriptionInfo.getPrescriptionType())) {
                        feeType = FeeTypeEnum.CAOYAO.getTitle();
                        feeTypeName = FeeTypeEnum.CAOYAO.getContext();
                    }

                    feeRecord.setFeeTypeCode(feeType);
                    feeRecord.setFeeTypeName(feeTypeName);
                    feeRecords.add(feeRecord);
                }
            }
            request.setFeeRecords(feeRecords);
        }
    }

    /**
     * @description: 保存检验检查费用信息
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/11/17 13:29
     * @param: request
     * @param: expenseIdList
     * @return: void
     */
    public void setConfirmExpenseXmlRequest(PrecalculatedFeeRequestBean request, List<String> expenseIdList) throws ControllerException {
        //保存处置信息
        if (CommonUtils.isNotEmpty(expenseIdList)) {
            //his处置列表
            List<NewGetPrecalculatedFeeRequestBean.FeeRecordsBean> feeRecords = request.getFeeRecords();
            if (null == feeRecords) {
                feeRecords = new ArrayList<>();
            }
            //his处置对象
            NewGetPrecalculatedFeeRequestBean.FeeRecordsBean feeRecord;


            //线上处置列表
            List<OdsOrderExpenseRecord> disposalExpenseRecords = odsOrderExpenseRecordDAO.findByOrderId(request.getOrderId());
            if (CommonUtils.isNotEmpty(disposalExpenseRecords)) {
                for (OdsOrderExpenseRecord odsOrderExpenseRecord : disposalExpenseRecords) {
                    feeRecord = new NewGetPrecalculatedFeeRequestBean.FeeRecordsBean();
                    feeRecord.setFeeTypeCode(odsOrderExpenseRecord.getBillCategoryCode());
                    feeRecord.setFeeTypeName(FeeTypeEnum.getDescriptionContext(odsOrderExpenseRecord.getBillCategoryCode()));
                    feeRecord.setFeeNo(odsOrderExpenseRecord.getExpenseIdSource());
                    feeRecords.add(feeRecord);
                }
            }
            request.setFeeRecords(feeRecords);
        }
    }


    /**
     * @Author:FangZhiyi
     * @Description 按订单号查询物流
     * @Params [orderIdOutter]
     * @Return com.bsoft.hessian.entity.BaseResponse
     * @Data Created in 2020/9/5 21:07
     * @Moddified By:
     */
    @Override
    public BaseResponse queryLogistics(String orderNo) {
        try {
            String result = OperationPlatformSignUtil.signGet(null, OperationPlatformSignUtil.QUERY_LOGISTICS + orderNo);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (ResultCode.SUCCESS == resultJson.getIntValue("code")) {
                QueryLogisticsResp queryLogisticsResp = JSONObject.parseObject(resultJson.getJSONObject("body").toJSONString(), QueryLogisticsResp.class);
                return BaseRespUtil.setResultSuccess(queryLogisticsResp);
            }
            return BaseRespUtil.setResultError("查询失败:" + resultJson.getString("msg"));
        } catch (IOException e) {
            e.printStackTrace();
            return BaseRespUtil.setResultError("查询失败：" + e.getMessage());
        }
    }

    /**
     * 查询快递信息
     *
     * @param orderNo 订单编号
     * @return 快递信息
     */
    @Override
    public List<ExpreeInfoVo> queryExpressInfo(String orderNo) throws ControllerException {
        List<ExpreeInfoVo> expreeInfoVoList = Lists.newArrayList();
        OdsExpressInfo odsExpressInfo = odsExpressInfoDAO.getOdsExpressInfo(orderNo);
        if (odsExpressInfo == null) {
            return expreeInfoVoList;
        }

        //若是院外查询处方流转平台快递信息
        if (Constants.TWO.toString().equals(odsExpressInfo.getTransferType())) {
            BaseResponse response = this.queryLogistics(orderNo);
            if (CommonUtils.isNotEmpty(response.getData())) {
                QueryLogisticsResp queryLogisticsResp = (QueryLogisticsResp) response.getData();
                if (CommonUtils.isNotEmpty(queryLogisticsResp.getTransports())) {
                    ExpreeInfoVo expreeInfoVo = new ExpreeInfoVo();
                    expreeInfoVo.setExpreeCompanyCode(queryLogisticsResp.getTransports().getCompanyCode());
                    expreeInfoVo.setExpreeNumber(queryLogisticsResp.getTransports().getNumber());
                    ExpressCompany expressCompany = expressFeeService.getExpressCompanyByCode(queryLogisticsResp.getTransports().getCompanyCode());
                    if (expressCompany != null) {
                        expreeInfoVo.setExpreeCompanyName(expressCompany.getExpressName());
                    }
                    expreeInfoVoList.add(expreeInfoVo);
                }
            }
            return expreeInfoVoList;
        }

        //查询院内的快递信息
        List<QueryDrugOrderExpressInfoListVo> queryExpressOrderDetailList = expreeOrderDAO.queryExpressOrderDetailList(orderNo);
        if (CommonUtils.isNotEmpty(queryExpressOrderDetailList)) {
            for (QueryDrugOrderExpressInfoListVo qv : queryExpressOrderDetailList) {
                ExpreeInfoVo expreeInfoVo = new ExpreeInfoVo();
                ExpressCompany expressCompany = expressFeeService.getExpressCompanyByCode(qv.getExpressCode());
                if (CommonUtils.isNotEmpty(expressCompany)) {
                    expreeInfoVo.setExpreeCompanyName(expressCompany.getExpressName());
                }
                expreeInfoVo.setExpreeCompanyCode(qv.getExpressCode());
                expreeInfoVo.setExpreeNumber(qv.getExpressNumber());
                expreeInfoVo.setDeliverFlag(qv.getExpressStatus());
                expreeInfoVoList.add(expreeInfoVo);
            }
        }
        return expreeInfoVoList;
    }

    /**
     * @Author:FangZhiyi
     * @Description 订单取消
     * @Params [orderIdOutter]
     * @Return com.bsoft.hessian.entity.BaseResponse
     * @Data Created in 2020/8/5 21:07
     * @Moddified By:
     */
    @Override
    public BaseResponse cancelPrescriptionOrder(String orderIdOutter, String orderId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderIdOutter", orderIdOutter);
        try {
            String result = OperationPlatformSignUtil.signPost(jsonObject.toJSONString(), OperationPlatformSignUtil.CANCEL);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (ResultCode.SUCCESS == resultJson.getIntValue("code")) {
                List<OdsOrderPrescriptionInfo> odsOrderPrescriptionInfoList = odsOrderPrescriptionInfoDAO.findByOrderId(orderId);
                if (!CollectionUtils.isEmpty(odsOrderPrescriptionInfoList)) {
                    for (OdsOrderPrescriptionInfo odsOrderPrescriptionInfo : odsOrderPrescriptionInfoList) {
                        OdsOrderPrescriptionInfoVo odsOrderPrescriptionInfoVo = new OdsOrderPrescriptionInfoVo();
                        BeanUtils.copy(odsOrderPrescriptionInfo, odsOrderPrescriptionInfoVo);
                        this.revokeRecipe(odsOrderPrescriptionInfoVo, 1);
                    }
                }
                return BaseRespUtil.setResultSuccess();
            }
            return BaseRespUtil.setResultError("取消失败:" + resultJson.getString("msg"));
        } catch (IOException e) {
            e.printStackTrace();
            return BaseRespUtil.setResultError("取消失败：" + e.getMessage());
        }
    }

    /**
     * @description: 处方信息数据转换
     * @author: chenJij@bsoft.com.cn
     * @date: 2022/11/15 17:09
     * @param: odsOrderPrescriptionInfoVoList
     * @param: drugIOrdersVo
     * @param: storeDrugList
     * @param: type 1处方上传    2 订单上传   3 药品配送费
     * @return: java.util.List<pcn.bean.operationPlatform.request.RecipeInfoPro>
     */
    private List<RecipeInfoPro> recipeInfoChang(List<OdsOrderPrescriptionInfoVo> odsOrderPrescriptionInfoVoList, DrugIOrdersQo drugIOrdersVo, List<DrugIOrdersQo.StoreDrug> storeDrugList, String type) throws ControllerException {
        Map<String, String> storeDrugIdMap = null;
        //医院药品id作为key，药店药品id作为value
        if (CommonUtils.isNotEmpty(storeDrugList)) {
            storeDrugIdMap = new HashMap<>();
            for (DrugIOrdersQo.StoreDrug storeDrug : storeDrugList) {
                storeDrugIdMap.put(storeDrug.getDrugId(), storeDrug.getDrugCode());
            }
        }
        List<RecipeInfoPro> recipeInfo = new ArrayList<>();
        for (OdsOrderPrescriptionInfoVo odsOrderPrescriptionInfoVo : odsOrderPrescriptionInfoVoList) {
            //已上传的处方不用再上传
            if ("1".equals(odsOrderPrescriptionInfoVo.getPlatformRecipeStatus()) && "1".equals(type)) {
                continue;
            }
            RecipeInfoPro recipeInfoPro = new RecipeInfoPro();
            recipeInfoPro.setRecipeIdOutter(odsOrderPrescriptionInfoVo.getPrescriptionNumber());
            recipeInfoPro.setDoctorIdOutter(odsOrderPrescriptionInfoVo.getDoctorId());
            recipeInfoPro.setDoctorNameOutter(odsOrderPrescriptionInfoVo.getDoctorName());
            DoctInfo doctInfo = null;
            try {
                doctInfo = doctorInfoService.getDocInfo(odsOrderPrescriptionInfoVo.getDoctorId());
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (doctInfo != null) {
                //国产化加密存储 解密
                recipeInfoPro.setDoctorPhone(SM4Utils.decryptData_ECB(doctInfo.getPhoneNo()));
                recipeInfoPro.setDoctorIdcard(SM4Utils.decryptData_ECB(doctInfo.getIdCard()));
            }
            recipeInfoPro.setReviewerIdOutter(odsOrderPrescriptionInfoVo.getAuditDoctorId());
            recipeInfoPro.setReviewerNameOutter(odsOrderPrescriptionInfoVo.getAuditor());
            //自动审方医生没有doctorId
            if (CommonUtils.isNotEmpty(odsOrderPrescriptionInfoVo.getAuditDoctorId())) {
                try {
                    doctInfo = doctorInfoService.getDocInfo(odsOrderPrescriptionInfoVo.getAuditDoctorId());
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (doctInfo != null) {
                    recipeInfoPro.setReviewerPhone(SM4Utils.decryptData_ECB(doctInfo.getPhoneNo()));
                    recipeInfoPro.setReviewerIdcard(SM4Utils.decryptData_ECB(doctInfo.getIdCard()));
                }
            }

            recipeInfoPro.setPrescriptionTime(odsOrderPrescriptionInfoVo.getCreateTime());//开方时间
            if ("1".equals(odsOrderPrescriptionInfoVo.getPrescriptionType())) {
                recipeInfoPro.setRecipeTypeCode("21");
            } else {
                recipeInfoPro.setRecipeTypeCode("23");
                recipeInfoPro.setMedicineCount(odsOrderPrescriptionInfoVo.getNumberOfPackets() + "");
                recipeInfoPro.setDecoctingPackNum(odsOrderPrescriptionInfoVo.getNumberOfPackets() + "");
                if (drugIOrdersVo != null) {
                    Integer boilFlag = Integer.valueOf(drugIOrdersVo.getBoilFlag());
                    recipeInfoPro.setNeedDecocting(boilFlag);
                    if (boilFlag == 1) {
                        //代煎
                        recipeInfoPro.setDecoctingPackCapacity(drugIOrdersVo.getDecoctingPackCapacity());
                    }
                }
            }

            Map<String, String> collect = null;
            List<BaseDicItem> baseDicItems = dicContrastService.findDictionaryItemList(1, "system", "outer_packaging_unit");
            if (CommonUtils.isNotEmpty(baseDicItems)) {
                collect = baseDicItems.stream().collect(Collectors.toMap(BaseDicItem::getItemName, BaseDicItem::getItemCode));
            }

            recipeInfoPro.setRecipe_conclusion("");//合理用药信息
            List<DrudDetail> detailsList = new ArrayList<>();
            List<OdsOrderPrescriptionDrug> odsPrescriptionDrugs = odsOrderPrescriptionInfoVo.getOrderPrescriptionDrugList();
            if (!CollectionUtils.isEmpty(odsPrescriptionDrugs)) {
                for (OdsOrderPrescriptionDrug prescriptionDrug : odsPrescriptionDrugs) {
                    DrudDetail drudDetail = new DrudDetail();
                    drudDetail.setDrugDays(prescriptionDrug.getTakeDays());//用药天数
                    //若是药店药品不为空，那么需要把处方内的药品id换成药店的药品id
                    if (null != storeDrugIdMap) {
                        //药店药品ID
                        drudDetail.setDrugCode(storeDrugIdMap.get(prescriptionDrug.getOrgDrugId()));
                    } else {
                        //医院药品ID
                        drudDetail.setDrugCode(prescriptionDrug.getOrgDrugId());
                    }
                    drudDetail.setDrugDose(prescriptionDrug.getDose().toString());//单次使用剂量
                    //剂量单位需要字典转换
                    drudDetail.setDoseUnitTxt(prescriptionDrug.getDoseUnit());//剂量单位
                    drudDetail.setDrugPathwaysTxt(prescriptionDrug.getUsageName());//用药方法编码
                    //用药频次编码需要字典转换
                    drudDetail.setDrugRateTxt(prescriptionDrug.getFrequencyName());//用药频次编码
                    drudDetail.setDrugId(Integer.valueOf(prescriptionDrug.getOrgDrugId()));//药品ID
                    drudDetail.setDrugName(prescriptionDrug.getOrgDrugName());//药品名称
                    drudDetail.setGeneralName(prescriptionDrug.getOrgDrugName());//药品名称
                    drudDetail.setSpecDesc(prescriptionDrug.getSpecification());//规格描述
                    drudDetail.setSpecId(0);//规格ID
                    //包装单位编码需要字典转换
                    String itemCode = null;
                    if (null != collect) {
                        itemCode = collect.get(prescriptionDrug.getPackUnit());
                    }
                    if (CommonUtils.isEmpty(itemCode)) {
                        throw new ControllerException("未找到外包装单位（" + prescriptionDrug.getPackUnit() + "）配置,院外药店下单失败");
                    }
                    drudDetail.setPackUnitOutter(itemCode);//包装单位编码
                    drudDetail.setPackUnitOutterTxt(prescriptionDrug.getPackUnit());//包装单位编码
                    drudDetail.setPackQtyOutter(prescriptionDrug.getQuantity().toString());//包装数量
                    drudDetail.setAmount(prescriptionDrug.getPrice().multiply(prescriptionDrug.getQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP).toString());
                    drudDetail.setPrice(prescriptionDrug.getPrice().toString());
                    drudDetail.setQty(prescriptionDrug.getQuantity().toString());
                    drudDetail.setCommercialId(Integer.valueOf(prescriptionDrug.getOrgDrugId()));
                    detailsList.add(drudDetail);
                }
            }
            recipeInfoPro.setDetails(detailsList);
            recipeInfo.add(recipeInfoPro);
        }
        return recipeInfo;
    }

    public IMPIProvider getHcnMpiProvider() {
        return hcnMpiProvider;
    }

    public void setHcnMpiProvider(IMPIProvider hcnMpiProvider) {
        this.hcnMpiProvider = hcnMpiProvider;
    }

    /**
     * @description: 撤回处方
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30
     * @param: odsOrderPrescriptionInfoVo
     * @param: times
     * @return: void
     */
    public void revokeRecipe(OdsOrderPrescriptionInfoVo odsOrderPrescriptionInfoVo, int times) {

        times++;
        RecipeRevokeReq revokeReq = new RecipeRevokeReq();
        revokeReq.setRecipeIdOutter(odsOrderPrescriptionInfoVo.getPrescriptionNumber());
        revokeReq.setOperateDt(new Date());
        String param = JSONObject.toJSONStringWithDateFormat(revokeReq, JSON.DEFFAULT_DATE_FORMAT);
        String result = null;
        try {
            result = OperationPlatformSignUtil.signPost(param, OperationPlatformSignUtil.REVOKE);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (ResultCode.SUCCESS != resultJson.getIntValue("code")) {
                if (times <= 3) {
                    logger.warn("处方撤回失败:" + odsOrderPrescriptionInfoVo.getPrescriptionNumber() + "请求第" + times + "次撤回");
                    this.revokeRecipe(odsOrderPrescriptionInfoVo, times);
                }
            } else {
                OdsPrescriptionInfo odsPrescriptionInfo = prescriptionInfoIntf.getOdsPrescriptionInfo(odsOrderPrescriptionInfoVo.getPrescriptionInfoId());
                /*更新处方表的上传状态*/
                odsPrescriptionInfo.setPlatformRecipeStatus("2");
                prescriptionInfoIntf.updateOdsPrescriptionInfo(odsPrescriptionInfo);
                logger.info("处方撤回成功:" + odsPrescriptionInfo.getPrescriptionNumber());
            }
        } catch (IOException e) {
            e.printStackTrace();
            logger.warn("处方撤回报错:" + odsOrderPrescriptionInfoVo.getPrescriptionNumber() + e.getMessage());
            if (times <= 3) {
                logger.warn("处方撤回失败:" + odsOrderPrescriptionInfoVo.getPrescriptionNumber() + "请求第" + times + "次撤回");
                this.revokeRecipe(odsOrderPrescriptionInfoVo, times);
            }
        } catch (ControllerException e) {
            e.printStackTrace();
            logger.warn("处方撤回报错:" + odsOrderPrescriptionInfoVo.getPrescriptionNumber() + e.getMessage());
            if (times <= 3) {
                logger.warn("处方撤回失败:" + odsOrderPrescriptionInfoVo.getPrescriptionNumber() + "请求第" + times + "次撤回");
                this.revokeRecipe(odsOrderPrescriptionInfoVo, times);
            }
        }

    }

    /**
     * @Author:FangZhiyi
     * @Description 获取流转平台快递费用
     * @Params [queryFareReq]
     * @Return pcn.bean.operationPlatform.response.QueryFareResp
     * @Data Created in 2020/10/16 22:08
     * @Moddified By:
     */
    @Override
    public QueryFareResp queryFare(QueryFareReq queryFareReq) throws ControllerException {
        QueryFareResp queryFareResp = new QueryFareResp();
        if (!CollectionUtils.isEmpty(queryFareReq.getPrescriptionIdList()) && CollectionUtils.isEmpty(queryFareReq.getPlanInfos())) {
            DrugIOrdersQo drugIOrdersQo = new DrugIOrdersQo();
            drugIOrdersQo.setOrgId(queryFareReq.getOrgId());
            drugIOrdersQo.setPrescriptionIdList(queryFareReq.getPrescriptionIdList());
            drugIOrdersQo.setOutpatientType(queryFareReq.getOutpatientType());
            List<OdsOrderPrescriptionInfoVo> odsOrderPrescriptionInfoVos = queryOrderPrescriptionInfoList(drugIOrdersQo);
            List<RecipeInfoPro> recipeInfoProList = recipeInfoChang(odsOrderPrescriptionInfoVos, null, null, "3");
            for (RecipeInfoPro recipeInfoPro : recipeInfoProList) {
                recipeInfoPro.setNeedDecocting(queryFareReq.getNeedDecocting());
                recipeInfoPro.setDecoctingPackCapacity(queryFareReq.getDecoctingPackCapacity());
            }
            queryFareReq.setPlanInfos(recipeInfoProList);

        }
        String param = JSONObject.toJSONStringWithDateFormat(queryFareReq, JSON.DEFFAULT_DATE_FORMAT);
        try {
            String result = OperationPlatformSignUtil.signPost(param, OperationPlatformSignUtil.QUERY_FARE);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (ResultCode.SUCCESS == resultJson.getIntValue("code")) {
                queryFareResp = JSONObject.parseObject(resultJson.getJSONObject("body").toJSONString(), QueryFareResp.class);
                return queryFareResp;
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new ControllerException("查询处方流转快递费失败:" + e.getMessage());
        }
        return queryFareResp;
    }

    /**
     * @Author:FangZhiyi
     * @Description 获取快递费用（院内药房）
     * @Params [queryFareReq]
     * @Return pcn.bean.operationPlatform.response.ExpressCostResp
     * @Data Created in 2020/10/16 21:30
     * @Moddified By:
     */
    @Override
    public ExpressCostResp getExpressCost(ExpressCostReq queryFareReq) throws ControllerException {
        ExpressCostResp expressCostResp = new ExpressCostResp();

        if (CommonUtils.isEmpty(queryFareReq.getProvinceCode())) {
            throw new ControllerException("省行政区域代码不能为空");
        }
        if (CommonUtils.isEmpty(queryFareReq.getCityCode())) {
            throw new ControllerException("市行政区域代码不能为空");
        }

        //草药药品总数量
        BigDecimal chineseDrugNumber = new BigDecimal(0);
        //西药、中成药药品总数量
        BigDecimal drugNumber = new BigDecimal(0);

        if (CommonUtils.isNotEmpty(queryFareReq.getPrescriptionIdList())) {

            //查询要支付的全部处方
            List<OdsPrescriptionInfo> odsPrescriptionInfoList = prescriptionInfoIntf.queryByFeeNoList(queryFareReq.getPrescriptionIdList());

            if (CommonUtils.isNotEmpty(odsPrescriptionInfoList)) {
                for (OdsPrescriptionInfo odsPrescriptionInfo : odsPrescriptionInfoList) {
                    //查询处方的药品列表
                    List<OdsPrescriptionDrug> odsPrescriptionDrugs = prescriptionInfoIntf.findByPrescriptionInfoId(odsPrescriptionInfo.getPrescriptionInfoId());
                    if (CommonUtils.isNotEmpty(odsPrescriptionDrugs)) {
                        for (OdsPrescriptionDrug odsPrescriptionDrug : odsPrescriptionDrugs) {
                            //若是西药或者中成药就直接把药品数量相加
                            if (DrugTypeEnum.XIYAO.getCode().equals(odsPrescriptionInfo.getPrescriptionType()) || DrugTypeEnum.ZHONGYAO.getCode().equals(odsPrescriptionInfo.getPrescriptionType())) {
                                drugNumber = drugNumber.add(odsPrescriptionDrug.getQuantity());
                            }
                        }
                    }
                    if (DrugTypeEnum.CAOYAO.getCode().equals(odsPrescriptionInfo.getPrescriptionType())) {
                        chineseDrugNumber = chineseDrugNumber.add(new BigDecimal(odsPrescriptionInfo.getNumberOfPackets()));
                    }
                }
            } else {
                DrugIOrdersQo drugIOrdersQo = new DrugIOrdersQo();
                drugIOrdersQo.setOrgId(queryFareReq.getOrgId());
                drugIOrdersQo.setPrescriptionIdList(queryFareReq.getPrescriptionIdList());
                drugIOrdersQo.setVisitIdList(queryFareReq.getVisitIdList());
                drugIOrdersQo.setOutpatientType(queryFareReq.getOutpatientType());
                List<OdsOrderPrescriptionInfoVo> odsOrderPrescriptionInfoVos = queryOrderPrescriptionInfoList(drugIOrdersQo);
                if (CommonUtils.isNotEmpty(odsOrderPrescriptionInfoVos)) {
                    for (OdsOrderPrescriptionInfoVo odsOrderPrescriptionInfoVo : odsOrderPrescriptionInfoVos) {
                        for (OdsOrderPrescriptionDrug odsOrderPrescriptionDrug : odsOrderPrescriptionInfoVo.getOrderPrescriptionDrugList()) {
                            //若是西药或者中成药就直接把药品数量相加
                            if (DrugTypeEnum.XIYAO.getCode().equals(odsOrderPrescriptionInfoVo.getPrescriptionType()) || DrugTypeEnum.ZHONGYAO.getCode().equals(odsOrderPrescriptionInfoVo.getPrescriptionType())) {
                                drugNumber = drugNumber.add(odsOrderPrescriptionDrug.getQuantity());
                            }
                        }
                        if (DrugTypeEnum.CAOYAO.getCode().equals(odsOrderPrescriptionInfoVo.getPrescriptionType())) {
                            chineseDrugNumber = chineseDrugNumber.add(new BigDecimal(odsOrderPrescriptionInfoVo.getNumberOfPackets()));
                        }
                    }
                }
            }
        }

        BigDecimal totalCharges = new BigDecimal(0);
        //若是西药药品数量不为空
        if (drugNumber.doubleValue() > 0) {
            totalCharges = totalCharges.add(countExpressFee(queryFareReq, (byte) 1, drugNumber.doubleValue()));
        }
        //若是草药药品数量不为空
        if (chineseDrugNumber.doubleValue() > 0) {
            totalCharges = totalCharges.add(countExpressFee(queryFareReq, (byte) 2, chineseDrugNumber.doubleValue()));
        }
        expressCostResp.setExpressCost(totalCharges.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
        return expressCostResp;
    }


    /**
     * @description: 根据快递物流配置查询快递费
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/10/19 16:30
     */
    private BigDecimal countExpressFee(ExpressCostReq queryFareReq, Byte drugType, double drugNumber) throws ControllerException {
        //物流总费用
        BigDecimal totalCharges = new BigDecimal(0);
        //包装费
        BigDecimal packCharges = new BigDecimal(0);
        //配送费
        BigDecimal deliveryCharges = new BigDecimal(0);

        //查找药品配送的规则
        SysBillingRule sysPayCofByModeCode = expressFeeService.getSysPayCofByModeCode(queryFareReq.getOrgId(), queryFareReq.getModuleId(), queryFareReq.getDeliveryModeCode(), drugType);
        if (null == sysPayCofByModeCode) {
            throw new ControllerException("未查到该机构的药品配送配置");
        }

        //查找药品配送规则
        ExpressFeeRule expressFeeRule = expressFeeService.getExpressFeeRule(sysPayCofByModeCode.getBillingRule());
        if (null == expressFeeRule) {
            throw new ControllerException("未查到的物流配送配置");
        }

        //查询区域的物流配置
        List<ExpressModeRule> list = expressFeeService.findExpressModeRuleByRuleId(sysPayCofByModeCode.getBillingRule());
        if (CommonUtils.isEmpty(list)) {
            throw new ControllerException("未查到该区域的物流配送配置");
        }
        //该区域的物流配置
        ExpressModeRule cityExpressModeRule = null;

        for (ExpressModeRule rule : list) {
            //若是行政区域编码一致,则获取该编码
            if (rule.getProvinceCode().equals(queryFareReq.getProvinceCode()) && rule.getCityCode().contains(queryFareReq.getCityCode())) {
                cityExpressModeRule = rule;
            }
        }

        if (null == cityExpressModeRule) {
            throw new ControllerException("未查到的该区域的物流配送配置");
        }

        //若是配置是计重
        if (Constants.UNIT_WEIGHT.equals(expressFeeRule.getRuleType())) {
            BigDecimal totalWeight = new BigDecimal(0);

            if (null == sysPayCofByModeCode.getDrugWeight()) {
                throw new ControllerException("药品均重不能为空");
            }

            //药品总总量
            totalWeight = totalWeight.add(new BigDecimal(drugNumber).multiply(new BigDecimal(sysPayCofByModeCode.getDrugWeight())));

            //计重逻辑
            //1.包装费 = 订单总重/每箱重量*每箱包装费
            BigDecimal unitWeight = totalWeight.divide(new BigDecimal(expressFeeRule.getUnitWeight()), 0, BigDecimal.ROUND_UP);

            packCharges = unitWeight.multiply(expressFeeRule.getUnitPrice());

            //2.配送费
            //if 订单总重 <=  首重 ： 配送费 = 对应地区首重费用
            //if 订单总重 > 首重：配送费 =  对应地区首重费用 + （订单总重-首重）/续重*对应地区续重费用
            if (totalWeight.doubleValue() <= expressFeeRule.getFirstWeight().doubleValue()) {
                deliveryCharges = cityExpressModeRule.getFirstWeightPrice();
            } else {
                BigDecimal leftWeight = totalWeight.subtract(new BigDecimal(expressFeeRule.getFirstWeight()));
                BigDecimal continueWeight = leftWeight.divide(new BigDecimal(expressFeeRule.getContinuedWeight()), 0, BigDecimal.ROUND_UP);

                deliveryCharges = cityExpressModeRule.getFirstWeightPrice().add(continueWeight.multiply(cityExpressModeRule.getContinuedWeightPrice()));
            }

            //3.物流总费用 = 包装费 + 配送费
            totalCharges = totalCharges.add(packCharges.add(deliveryCharges));

            //若是配置是计件
        } else if (Constants.UNIT_NUM.equals(expressFeeRule.getRuleType())) {
            List<String> modeIds = new ArrayList<>();
            modeIds.add(cityExpressModeRule.getModeId());
            //查询计件的件数价格区间列表
            List<ExpressSectionRule> sectionRules = expressFeeService.findSectionRule(modeIds);

            if (CommonUtils.isEmpty(sectionRules)) {
                throw new ControllerException("未查到的该区域的物流计件配送配置");
            }
            //件数的价格范围配置
            ExpressSectionRule expressSectionRule = null;
            for (ExpressSectionRule sectionRule : sectionRules) {
                //大于等于最小数量，小于等于最大数量
                if (null != sectionRule.getLowerLimit() && null != sectionRule.getUpperLimit()) {
                    if (drugNumber >= sectionRule.getLowerLimit().doubleValue() && drugNumber <= sectionRule.getUpperLimit().doubleValue()) {
                        expressSectionRule = sectionRule;
                    }
                    //大于等于最小数量
                } else if (null != sectionRule.getLowerLimit()) {
                    if (drugNumber >= sectionRule.getLowerLimit().doubleValue()) {
                        expressSectionRule = sectionRule;
                    }
                    //小于等于最大数量
                } else if (null != sectionRule.getUpperLimit()) {
                    if (drugNumber <= sectionRule.getUpperLimit().doubleValue()) {
                        expressSectionRule = sectionRule;
                    }
                }

            }
            if (null == expressSectionRule) {
                throw new ControllerException("未查到的该数量区间的的物流配送配置");
            }

            //计件逻辑
            //1.包装费 （订单总件数/每箱数量）*每箱包装费
            BigDecimal unitWeight = new BigDecimal(drugNumber).divide(new BigDecimal(expressFeeRule.getUnitWeight()), 0, BigDecimal.ROUND_UP);
            packCharges = unitWeight.multiply(expressFeeRule.getUnitPrice());

            //2.配送费 依据订单总件数与收货地址所在区域确定配送费
            deliveryCharges = expressSectionRule.getPrice();

            //3.物流总费用 = 包装费 + 配送费
            totalCharges = totalCharges.add(packCharges.add(deliveryCharges));

        }
        return totalCharges;
    }

    /**
     * @description: 从HIS获取代煎费
     * @author: chenJij@bsoft.com.cn
     * @date: 2021/8/30 13:30
     * @param: requestBean
     * @return: hcn.protocol.ods.returnVisit.DecocteResponseBean
     */
    @RpcService
    public DecocteResponseBean queryHerbalMedicineCost(DecocteRequestBean requestBean) throws ControllerException {

        if (CommonUtils.isEmpty(requestBean.getPrescriptionIdList())) {
            throw new ControllerException("处方标识不能为空");
        }
        BigDecimal totalNumber = new BigDecimal(0);
        BigDecimal amount = new BigDecimal(0);
        BigDecimal price = new BigDecimal(0);

        DecocteResponseBean decocteResponseBean = new DecocteResponseBean();
        //查询代煎费
        GetDecoctingFeeXMLReq decoctingFeeXMLReq = new GetDecoctingFeeXMLReq();
        decoctingFeeXMLReq.setVisitOrganization(requestBean.getOrgId());
        List<GetDecoctingFeeXMLReq.FeeNoDetail> feeNoLists = new ArrayList<>();
        for (String feeNo : requestBean.getPrescriptionIdList()) {
            GetDecoctingFeeXMLReq.FeeNoDetail feeNoDetail = new GetDecoctingFeeXMLReq.FeeNoDetail();
            feeNoDetail.setFeeNo(feeNo);
            feeNoLists.add(feeNoDetail);
        }
        decoctingFeeXMLReq.setFeeNoLists(feeNoLists);
        try {
            BaseResponse<GetDecoctingFeeXMLResp> baseResponse = diagnosisPayTradeService.getDecoctingFeeXML(decoctingFeeXMLReq);
            if (baseResponse.getCode() == 200) {
                GetDecoctingFeeXMLResp getDecoctingFeeXMLResp = new GetDecoctingFeeXMLResp();
                List<GetDecoctingFeeXMLResp.DecoctingFee> decoctingFeeList = getDecoctingFeeXMLResp.getRecords();
                if (!org.apache.commons.collections.CollectionUtils.isEmpty(decoctingFeeList)) {
                    for (GetDecoctingFeeXMLResp.DecoctingFee decoctingFee : decoctingFeeList) {
                        totalNumber = totalNumber.add(new BigDecimal(decoctingFee.getCostNumber()));
                        amount = amount.add(new BigDecimal(decoctingFee.getCostNumber()));
                        price = new BigDecimal(decoctingFee.getCostPrice());
                    }
                }
            }

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }


        decocteResponseBean.setPrice(price.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        decocteResponseBean.setItemNumber(totalNumber.intValue());
        decocteResponseBean.setUnit("贴");
        decocteResponseBean.setAmount(amount.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        return decocteResponseBean;
    }

    /**
     * @description: 获取处方笺
     * @author: chenJij@bsoft.com.cn
     * @date: 2019/12/4 12:49
     */
    @RpcService
    public QueryPrescriptionNotesVo queryPrescriptionNotes(QueryPrescriptionNotesQo qo) throws Exception {
        QueryPrescriptionNotesVo queryPrescriptionNotesVo = new QueryPrescriptionNotesVo();
        Person person = null;
        try {
            person = hcnMpiProvider.getPerson(qo.getPatientMpiId());
        } catch (MPIException e) {
            e.printStackTrace();
            throw new ControllerException("获取居民信息失败");
        }

        if (null == person) {
            throw new ControllerException("居民信息不存在");
        }
        //国产化加密存储 解密
        person = decryptData(person);
        Certificate certificate = person.getCertificate();
        if (null != certificate) {
            queryPrescriptionNotesVo.setIdCardNo(certificate.getCertificateNo());
        }
        if (null != person.getDob()) {
            queryPrescriptionNotesVo.setBirthday(DateUtils.toString(person.getDob(), "yyyy-MM-dd"));
        }
        queryPrescriptionNotesVo.setAddress(person.getAddress());

        if (null != queryPrescriptionNotesVo.getBirthday()) {
            queryPrescriptionNotesVo.setAge(DateUtils.getAgeByBirth(DateUtils.toDate(queryPrescriptionNotesVo.getBirthday())));
        }

        queryPrescriptionNotesVo.setPersonName(person.getPersonName());
        queryPrescriptionNotesVo.setPhoneNo(person.getPhoneNo());
        queryPrescriptionNotesVo.setSexCode(person.getSex());


        // type 1 展示健康档案的处方笺  2 展示医生下的处方 3.诊间支付的处方  4 诊间支付已支付列表
        //若是诊间支付，无需consultId
        if (Constants.THREE.toString().equals(qo.getType()) || Constants.FOUR.toString().equals(qo.getType())) {
            if (CommonUtils.isEmpty(qo.getPrescribeIdList())) {
                return queryPrescriptionNotesVo;
            }
            Organization organization = organizationInfoService.getOrgDetailByOrgId(qo.getOrgId());


            //诊间支付查看处方笺:3,待支付列表查看，4已支付列表查看
            PrescriptionRequest prescriptionRequest = new PrescriptionRequest();
            prescriptionRequest.setOrganizationId(organization.getLocalOrgId());
            prescriptionRequest.setPrescriptionId(qo.getPrescribeIdList().get(0));
            PrescriptionResponseTemporary prescriptionResponse = diagnosisInfoIntf.queryPrescriptionDetailHis(prescriptionRequest);
            this.buildPrescriptionNotesVo(queryPrescriptionNotesVo, qo.getType(), null, organization, prescriptionResponse);
            return queryPrescriptionNotesVo;
        }

        List<OdsOrderToPrescription> odsOrderToPrescriptions = null;

        //问诊记录标识赋值
        if (CommonUtils.isEmpty(qo.getConsultId()) && CommonUtils.isNotEmpty(qo.getOrderId())) {
            odsOrderToPrescriptions = odsOrderToPrescriptionDAO.findOrderToPrescriptionBy(qo.getOrderId());
            if (CommonUtils.isNotEmpty(odsOrderToPrescriptions)) {
                for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
                    if (CommonUtils.isNotEmpty(odsOrderToPrescription)) {
                        qo.setConsultId(odsOrderToPrescription.getConsultId());
                        break;
                    }
                }
            }
        }


        // type 1 展示健康档案的处方笺  2 展示医生下的处方 3.诊间支付的处方  4 诊间支付已支付列表
        // 若是健康通APP下处方
        if (Constants.TWO.toString().equals(qo.getType())) {

            ConsultAsk ask = null;
            Organization organization = null;

            if (CommonUtils.isEmpty(qo.getConsultId())) {
                throw new ControllerException("问诊记录id不能为空");
            }

            ask = consultAskServiceIntf.getConsultAsksByConsultId(qo.getConsultId());
            if (null == ask) {
                throw new ControllerException("该问诊记录不存在");
            }

            queryPrescriptionNotesVo.setPersonName(person.getPersonName());
            queryPrescriptionNotesVo.setPatientMedicalCardNumber(ask.getPatientMedicalCardNumber());

            if (null != ask.getCreateTime()) {
                queryPrescriptionNotesVo.setClinicTime(DateUtils.toString(ask.getCreateTime(), "yyyy-MM-dd"));
            }
            queryPrescriptionNotesVo.setClinicDept(ask.getDeptName());
            queryPrescriptionNotesVo.setClinicDoc(ask.getDoctorName());
            organization = organizationInfoService.getOrgDetailByOrgId(ask.getOrgId());
            queryPrescriptionNotesVo.setLocalOrgId(organization.getLocalOrgId());
            queryPrescriptionNotesVo.setOrgId(ask.getOrgId());
            queryPrescriptionNotesVo.setPhoneNo(ask.getPhoneNo());
            queryPrescriptionNotesVo.setSexCode(person.getSex());
            //添加诊断
            List<OdsDiagnosis> diagnosis = diagnosisInfoIntf.queryOdsDiagnosisListByConsultId(ask.getConsultId());
            if (CommonUtils.isNotEmpty(diagnosis)) {
                queryPrescriptionNotesVo.setClinicSymp(diagnosis.get(0).getDiseasesName());
            }

            try {
                if (CommonUtils.isEmpty(qo.getPatientMpiId())) {
                    throw new ControllerException("居民信息主索引不能为空");
                }

                List<OdsPrescriptionInfo> odsPrescriptionInfos = null;
                if (CommonUtils.isNotEmpty(qo.getPrescribeIdList())) {
                    if ("0".equals(qo.getQueryType())) {
                        odsPrescriptionInfos = prescriptionInfoIntf.queryByFeeNoList(qo.getPrescribeIdList());
                    } else {
                        odsPrescriptionInfos = prescriptionInfoIntf.queryPrescriptionByPrescriptionStatusAndId(qo.getPrescribeIdList());
                    }
                } else if (CommonUtils.isNotEmpty(qo.getOrderId())) {
                    List<String> prescribeIdList = new ArrayList<>();
                    if (CommonUtils.isNotEmpty(odsOrderToPrescriptions)) {
                        for (OdsOrderToPrescription odsOrderToPrescription : odsOrderToPrescriptions) {
                            if (FeeTypeEnum.XIYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CHENGYAO.getTitle().equals(odsOrderToPrescription.getFeeType()) || FeeTypeEnum.CAOYAO.getTitle().equals(odsOrderToPrescription.getFeeType())) {
                                prescribeIdList.add(odsOrderToPrescription.getFeeCode());//处方id
                            }
                        }
                    }

                    if (CommonUtils.isNotEmpty(prescribeIdList)) {
                        odsPrescriptionInfos = prescriptionInfoIntf.queryByFeeNoList(prescribeIdList);
                    }

                } else {
                    if ("0".equals(qo.getQueryType())) {
                        odsPrescriptionInfos = prescriptionInfoIntf.queryPrescriptionByConsultIdAndStatus(qo.getConsultId(), "0");
                    } else {
                        odsPrescriptionInfos = prescriptionInfoIntf.queryPrescriptionByConsultId(qo.getConsultId(), "1");
                    }

                }
                //中药处方列表
                List<QueryPrescriptionNotesVo.ChineseMedicineListBean> chineseMedicineList = null;
                //中药处方
                QueryPrescriptionNotesVo.ChineseMedicineListBean chineseMedicineListBean = null;
                //中药处方药品列表
                List<QueryPrescriptionNotesVo.ChineseMedicineListBean.MedicineListBean> medicineList = null;
                //中药处方药品
                QueryPrescriptionNotesVo.ChineseMedicineListBean.MedicineListBean medicineListBean;
                //西药、中成药处方列表
                List<QueryPrescriptionNotesVo.DrugListBean> drugListBeanList = null;
                //西药、中成药处方
                QueryPrescriptionNotesVo.DrugListBean drugListBean;
                //西药、中成药处方药品列表
                List<QueryPrescriptionNotesVo.DrugListBean.DrugDetailsBean> drugDetailsBeanList = null;
                //西药、中成药处方药品
                QueryPrescriptionNotesVo.DrugListBean.DrugDetailsBean drugDetailsBean;
                BigDecimal drugTotalFee = new BigDecimal(0);
                if (CommonUtils.isNotEmpty(odsPrescriptionInfos)) {
                    drugListBeanList = new ArrayList<>();
                    chineseMedicineList = new ArrayList<>();
                    for (OdsPrescriptionInfo odsPrescriptionInfo : odsPrescriptionInfos) {
                        ConsultAsk consultAsk = consultAskServiceIntf.getConsultAsksByConsultId(odsPrescriptionInfo.getConsultId());
                        if (null == consultAsk) {
                            throw new ControllerException("该问诊记录不存在");
                        }
                        //中药处方
                        if (PrescriptionTypeEnum.CHINESE_MEDICINE.getTitle().equals(odsPrescriptionInfo.getPrescriptionType())) {
                            chineseMedicineListBean = new QueryPrescriptionNotesVo.ChineseMedicineListBean();

                            if (null != consultAsk.getCreateTime()) {
                                chineseMedicineListBean.setClinicTime(DateUtils.toString(consultAsk.getCreateTime(), "yyyy-MM-dd"));
                            }
                            chineseMedicineListBean.setPersonName(person.getPersonName());
                            chineseMedicineListBean.setClinicDept(consultAsk.getDeptName());
                            chineseMedicineListBean.setClinicDoc(consultAsk.getDoctorName());
                            chineseMedicineListBean.setLocalOrgId(organization.getLocalOrgId());
                            chineseMedicineListBean.setOrgId(consultAsk.getOrgId());
                            chineseMedicineListBean.setIdCardNo(queryPrescriptionNotesVo.getIdCardNo());
                            chineseMedicineListBean.setOrgName(consultAsk.getOrgName());
                            chineseMedicineListBean.setPhoneNo(consultAsk.getPhoneNo());
                            chineseMedicineListBean.setSexCode(person.getSex());
                            chineseMedicineListBean.setClinicSymp(queryPrescriptionNotesVo.getClinicSymp());
                            chineseMedicineListBean.setAge(queryPrescriptionNotesVo.getAge());
                            chineseMedicineListBean.setPatientMedicalCardNumber(queryPrescriptionNotesVo.getPatientMedicalCardNumber());
                            chineseMedicineListBean.setAddress(queryPrescriptionNotesVo.getAddress());
                            chineseMedicineListBean.setBirthday(queryPrescriptionNotesVo.getBirthday());
                            chineseMedicineListBean.setPatientMedicalCardNumber(queryPrescriptionNotesVo.getPatientMedicalCardNumber());
                            chineseMedicineListBean.setNature("自费");

                            chineseMedicineListBean.setPrescriptionId(odsPrescriptionInfo.getPrescriptionNumber());
                            chineseMedicineListBean.setPrescriptionInfoId(odsPrescriptionInfo.getPrescriptionInfoId());
                            chineseMedicineListBean.setPrescriptionType(odsPrescriptionInfo.getPrescriptionType());
                            chineseMedicineListBean.setClinicSymp(consultAsk.getConfirmedDiagnosis());
                            chineseMedicineListBean.setTotalMedicine(odsPrescriptionInfo.getNumberOfPackets() == null ? 0 : odsPrescriptionInfo.getNumberOfPackets());

                            chineseMedicineListBean.setSeal(IMG_UPLOAD_URL + "/" + organization.getSealFileId());
                            //开方医生

                            DoctInfo doctor = doctorInfoService.getDocInfo(odsPrescriptionInfo.getDoctorId() == null ? "" : odsPrescriptionInfo.getDoctorId());
                            if (null != doctor) {
                                //开方医生姓名
                                chineseMedicineListBean.setDoctorName(doctor.getName());
                                //开方医生签名
                                chineseMedicineListBean.setPrescriptionDoctorSignature(doctor.getDoctorSignature());
                            } else {
                                //开方医生姓名
                                chineseMedicineListBean.setDoctorName(consultAsk.getDoctorName());
                            }


                            //审方药师
                            if (CommonUtils.isNotEmpty(odsPrescriptionInfo.getAuditDoctorId())) {
                                DoctInfo auditDoctor = doctorInfoService.getDocInfo(odsPrescriptionInfo.getAuditDoctorId());
                                if (null != auditDoctor) {
                                    //审方药师姓名
                                    chineseMedicineListBean.setAuditorName(auditDoctor.getName());
                                    //审方药师签名
                                    chineseMedicineListBean.setAuditPharmacistSignature(auditDoctor.getDoctorSignature());
                                } else {
                                    //审方药师姓名
                                    chineseMedicineListBean.setAuditorName(odsPrescriptionInfo.getAuditor());
                                }

                            } else {
                                //审方药师姓名
                                chineseMedicineListBean.setAuditorName(odsPrescriptionInfo.getAuditor());
                            }


                            if ("1".equals(odsPrescriptionInfo.getPayStatus())) {
                                chineseMedicineListBean.setOrderStatus("1");
                            } else if (null != odsPrescriptionInfo.getExpirationDate()) {
                                if (odsPrescriptionInfo.getExpirationDate().getTime() < System.currentTimeMillis()) {
                                    chineseMedicineListBean.setOrderStatus("2");
                                } else if ("1".equals(odsPrescriptionInfo.getOrderFlag())) {
                                    chineseMedicineListBean.setOrderStatus("1");
                                } else {
                                    chineseMedicineListBean.setOrderStatus("0");
                                    long time = 0;
                                    try {
                                        time = DateUtils.getCountTimeMillis(new Date(), odsPrescriptionInfo.getExpirationDate());
                                        chineseMedicineListBean.setRemainingSeconds(time);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                            //获取药品列表
                            List<OdsPrescriptionDrug> odsPrescriptionDrugList = prescriptionInfoIntf.findByPrescriptionInfoId(odsPrescriptionInfo.getPrescriptionInfoId());
                            if (CommonUtils.isNotEmpty(odsPrescriptionDrugList)) {
                                medicineList = new ArrayList<>();
                                BigDecimal totalFee = new BigDecimal(0);
                                for (OdsPrescriptionDrug odsPrescriptionDrug : odsPrescriptionDrugList) {
                                    medicineListBean = new QueryPrescriptionNotesVo.ChineseMedicineListBean.MedicineListBean();
                                    medicineListBean.setDrugId(String.valueOf(odsPrescriptionDrug.getDrugId()));
                                    medicineListBean.setDrugName(odsPrescriptionDrug.getDrugName());
                                    medicineListBean.setQuantity(Double.valueOf(String.valueOf(odsPrescriptionDrug.getQuantity() == null ? 0 : odsPrescriptionDrug.getQuantity())));
                                    medicineListBean.setPackUnit(odsPrescriptionDrug.getPackUnit());
                                    medicineListBean.setDecoctionCode(odsPrescriptionDrug.getDecoctionCode());
                                    medicineListBean.setDecoctionName(odsPrescriptionDrug.getDecoctionName());
                                    medicineListBean.setSpecification(odsPrescriptionDrug.getSpecification());
                                    double price = odsPrescriptionDrug.getPrice() == null ? 0 : odsPrescriptionDrug.getPrice().doubleValue();
                                    medicineListBean.setPrice(price);
                                    chineseMedicineListBean.setFrequencyName(odsPrescriptionDrug.getFrequencyName());
                                    chineseMedicineListBean.setFrequencyCode(odsPrescriptionDrug.getFrequencyCode());
                                    chineseMedicineListBean.setUsageCode(odsPrescriptionDrug.getUsageCode());
                                    chineseMedicineListBean.setTreatment(odsPrescriptionDrug.getUsageName());
                                    medicineList.add(medicineListBean);
                                    BigDecimal medicineTotalFee = new BigDecimal(price).multiply(new BigDecimal(Double.valueOf(String.valueOf(odsPrescriptionDrug.getQuantity() == null ? 0 : odsPrescriptionDrug.getQuantity())))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    totalFee = totalFee.add(medicineTotalFee.multiply(new BigDecimal(Double.valueOf(String.valueOf(odsPrescriptionInfo.getNumberOfPackets() == null ? 0 : odsPrescriptionInfo.getNumberOfPackets())))));
                                    drugTotalFee = drugTotalFee.add(medicineTotalFee.multiply(new BigDecimal(Double.valueOf(String.valueOf(odsPrescriptionInfo.getNumberOfPackets() == null ? 0 : odsPrescriptionInfo.getNumberOfPackets())))));
                                }
                                chineseMedicineListBean.setTotalFee(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                            }
                            chineseMedicineListBean.setMedicineList(medicineList);
                            chineseMedicineList.add(chineseMedicineListBean);
                        } else {
                            drugListBean = new QueryPrescriptionNotesVo.DrugListBean();

                            drugListBean.setPersonName(person.getPersonName());
                            if (null != consultAsk.getCreateTime()) {
                                drugListBean.setClinicTime(DateUtils.toString(consultAsk.getCreateTime(), "yyyy-MM-dd"));
                            }
                            drugListBean.setClinicDept(consultAsk.getDeptName());
                            drugListBean.setClinicDoc(consultAsk.getDoctorName());
                            drugListBean.setClinicSymp(queryPrescriptionNotesVo.getClinicSymp());
                            drugListBean.setPatientMedicalCardNumber(queryPrescriptionNotesVo.getPatientMedicalCardNumber());
                            drugListBean.setLocalOrgId(organization.getLocalOrgId());
                            drugListBean.setOrgId(consultAsk.getOrgId());
                            drugListBean.setIdCardNo(queryPrescriptionNotesVo.getIdCardNo());
                            drugListBean.setPhoneNo(consultAsk.getPhoneNo());
                            drugListBean.setOrgName(consultAsk.getOrgName());
                            drugListBean.setSexCode(person.getSex());
                            drugListBean.setAge(queryPrescriptionNotesVo.getAge());
                            drugListBean.setAddress(queryPrescriptionNotesVo.getAddress());
                            drugListBean.setBirthday(queryPrescriptionNotesVo.getBirthday());
                            drugListBean.setPatientMedicalCardNumber(queryPrescriptionNotesVo.getPatientMedicalCardNumber());
                            drugListBean.setNature("自费");

                            drugListBean.setPrescriptionId(odsPrescriptionInfo.getPrescriptionNumber());
                            drugListBean.setPrescriptionInfoId(odsPrescriptionInfo.getPrescriptionInfoId());
                            drugListBean.setPrescriptionType(odsPrescriptionInfo.getPrescriptionType());

                            drugListBean.setSeal(IMG_UPLOAD_URL + "/" + organization.getSealFileId());
                            //开方医生
                            DoctInfo doctor = doctorInfoService.getDocInfo(odsPrescriptionInfo.getDoctorId() == null ? "" : odsPrescriptionInfo.getDoctorId());
                            if (null != doctor) {
                                //开方医生姓名
                                drugListBean.setDoctorName(doctor.getName());
                                //开方医生签名
                                drugListBean.setPrescriptionDoctorSignature(doctor.getDoctorSignature());
                            } else {
                                //开方医生姓名
                                drugListBean.setDoctorName(consultAsk.getDoctorName());
                            }


                            //审方药师
                            if (CommonUtils.isNotEmpty(odsPrescriptionInfo.getAuditDoctorId())) {
                                DoctInfo auditDoctor = doctorInfoService.getDocInfo(odsPrescriptionInfo.getAuditDoctorId());
                                if (null != auditDoctor) {
                                    //审方药师姓名
                                    drugListBean.setAuditorName(auditDoctor.getName());
                                    //审方药师签名
                                    drugListBean.setAuditPharmacistSignature(auditDoctor.getDoctorSignature());
                                } else {
                                    //审方药师姓名
                                    drugListBean.setAuditorName(odsPrescriptionInfo.getAuditor());
                                }

                            } else {
                                //审方药师姓名
                                drugListBean.setAuditorName(odsPrescriptionInfo.getAuditor());
                            }

                            if ("1".equals(odsPrescriptionInfo.getPayStatus())) {
                                drugListBean.setOrderStatus("1");
                            } else if (null != odsPrescriptionInfo.getExpirationDate()) {
                                if (odsPrescriptionInfo.getExpirationDate().getTime() < System.currentTimeMillis()) {
                                    drugListBean.setOrderStatus("2");
                                } else if ("1".equals(odsPrescriptionInfo.getOrderFlag())) {
                                    drugListBean.setOrderStatus("1");
                                } else {
                                    drugListBean.setOrderStatus("0");
                                    long time = 0;
                                    try {
                                        time = DateUtils.getCountTimeMillis(new Date(), odsPrescriptionInfo.getExpirationDate());
                                        drugListBean.setRemainingSeconds(time);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }

                            //获取药品列表
                            List<OdsPrescriptionDrug> odsPrescriptionDrugList = prescriptionInfoIntf.findByPrescriptionInfoId(odsPrescriptionInfo.getPrescriptionInfoId());
                            if (CommonUtils.isNotEmpty(odsPrescriptionDrugList)) {
                                drugDetailsBeanList = new ArrayList<>();
                                BigDecimal totalFee = new BigDecimal(0);
                                for (OdsPrescriptionDrug odsPrescriptionDrug : odsPrescriptionDrugList) {
                                    drugDetailsBean = new QueryPrescriptionNotesVo.DrugListBean.DrugDetailsBean();
                                    drugDetailsBean.setDrugId(String.valueOf(odsPrescriptionDrug.getDrugId()));
                                    drugDetailsBean.setDrugName(odsPrescriptionDrug.getDrugName());
                                    drugDetailsBean.setQuantity(Double.valueOf(String.valueOf(odsPrescriptionDrug.getQuantity() == null ? 0 : odsPrescriptionDrug.getQuantity())));
                                    drugDetailsBean.setPackUnit(odsPrescriptionDrug.getPackUnit());
                                    drugDetailsBean.setFrequencyName(odsPrescriptionDrug.getFrequencyName());
                                    drugDetailsBean.setFrequencyCode(odsPrescriptionDrug.getFrequencyCode());
                                    drugDetailsBean.setUsageName(odsPrescriptionDrug.getUsageName());
                                    drugDetailsBean.setUsageCode(odsPrescriptionDrug.getUsageCode());
                                    drugDetailsBean.setDose(odsPrescriptionDrug.getDose() == null ? "0" : odsPrescriptionDrug.getDose().toString());
                                    drugDetailsBean.setDoseUnit(odsPrescriptionDrug.getDoseUnit());
                                    drugDetailsBean.setSpecification(odsPrescriptionDrug.getSpecification());
                                    double price = odsPrescriptionDrug.getPrice() == null ? 0 : odsPrescriptionDrug.getPrice().doubleValue();
                                    drugDetailsBean.setPrice(price);
                                    drugDetailsBeanList.add(drugDetailsBean);
                                    BigDecimal drugDetailTotalFee = new BigDecimal(price).multiply(new BigDecimal(Double.valueOf(String.valueOf(odsPrescriptionDrug.getQuantity() == null ? 0 : odsPrescriptionDrug.getQuantity())))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    totalFee = totalFee.add(drugDetailTotalFee);
                                    drugTotalFee = drugTotalFee.add(drugDetailTotalFee);
                                }
                                drugListBean.setTotalFee(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                            }
                            drugListBean.setDrugDetails(drugDetailsBeanList);
                            drugListBeanList.add(drugListBean);
                        }
                    }
                }
                if (CommonUtils.isNotEmpty(chineseMedicineList)) {
                    queryPrescriptionNotesVo.setChineseMedicineList(chineseMedicineList);
                }
                if (CommonUtils.isNotEmpty(drugListBeanList)) {
                    queryPrescriptionNotesVo.setDrugList(drugListBeanList);
                }
                queryPrescriptionNotesVo.setDrugTotalFee(drugTotalFee.doubleValue());

                return queryPrescriptionNotesVo;
            } catch (ControllerException e) {
                throw new ControllerException(e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                throw new ControllerException("获取处方笺失败");
            }
        } else {
            //健康档案查看处方笺
            try {
                OutpatientDateilRequestBean queryBean = new OutpatientDateilRequestBean();
                queryBean.setDcid(qo.getDcid());
                queryBean.setOrganizationId(qo.getLocalOrgId());
                //012213" text="复诊配药数据来源(1:区域平台,2:HIS),默认:1
                BasePropertyConfig propertyCode = serviceOpenService.getBasePropertyConfig("012213", RpcUserToken.getTenantId());

                OutpatientDateilBean outpatientDateilBean;
                if (null != propertyCode && "2".equals(propertyCode.getPropertyData())) {
                    outpatientDateilBean = clinicRecordsPlateformIntf.getOutpatientDateil(queryBean);
                } else {
                    outpatientDateilBean = clinicRecordsIntf.getOutpatientDateil(queryBean);
                }
                if (null != outpatientDateilBean) {
                    String data = JSONUtils.writeValueAsString(outpatientDateilBean);
                    data = data.replace("patientName", "personName").replace("pateintSex", "sexCode")
                            .replace("patientBirthday", "birthday").replace("departmentId", "localDeptId")
                            .replace("organizationId", "localOrgId").replace("organizationName", "orgName")
                            .replace("doctorName", "clinicDoc").replace("itemType", "drugType")
                            .replace("\"frequency\"", "\"frequencyName\"").replace("remark", "usageName")
                            .replace("medicineId", "drugId").replace("medicineName", "drugName")
                            .replace("\"decoction\"", "\"decoctionName\"").replace("drugId", "orgDrugId")
                            .replace("days", "takeDays")
                            .replace("route", "usageName").replace("auditorsName", "auditorName")
                            .replace("\"unit\"", "\"packUnit\"").replace("specifications", "specification")
                            .replace("departmentName", "clinicDept");


                    queryPrescriptionNotesVo = JSONObject.parseObject(data, QueryPrescriptionNotesVo.class);
                    //机构盖章url
                    String seal = null;
                    //查询本地机构
                    if (CommonUtils.isNotEmpty(queryPrescriptionNotesVo.getLocalOrgId())) {
                        Organization org = organizationInfoService.getOrgDetailByOrgCode(queryPrescriptionNotesVo.getLocalOrgId());
                        if (CommonUtils.isNotEmpty(org.getSealFileId())) {
                            seal = IMG_UPLOAD_URL + "/" + org.getSealFileId();
                        }
                    }
                    //建档档案的处方笺需要这些信息
                    if (null != certificate) {
                        queryPrescriptionNotesVo.setIdCardNo(certificate.getCertificateNo());
                    }

                    if (null != person.getDob()) {
                        queryPrescriptionNotesVo.setBirthday(DateUtils.toString(person.getDob(), "yyyy-MM-dd"));
                    }
                    queryPrescriptionNotesVo.setAddress(person.getAddress());

                    if (null != queryPrescriptionNotesVo.getClinicTime()) {
                        queryPrescriptionNotesVo.setClinicTime(DateUtils.toString(DateUtils.toDateForYYYYMMddHHmmss(queryPrescriptionNotesVo.getClinicTime()), "yyyy-MM-dd HH:mm:ss"));
                    }

                    if (null != queryPrescriptionNotesVo.getBirthday()) {
                        if (null != queryPrescriptionNotesVo.getClinicTime()) {
                            Date birthday = DateUtils.toDate(queryPrescriptionNotesVo.getBirthday());
                            Date clinicDate = DateUtils.toDate(queryPrescriptionNotesVo.getClinicTime(), "yyyy-MM-dd HH:mm:ss");
                            Integer agesByCountTimeMillis = DateUtils.getAgesByCountTimeMillis(birthday, clinicDate);
                            if (null != agesByCountTimeMillis && agesByCountTimeMillis > 0) {
                                queryPrescriptionNotesVo.setAge(agesByCountTimeMillis);
                            }
                        } else {
                            queryPrescriptionNotesVo.setAge(DateUtils.getAgeByBirth(DateUtils.toDate(queryPrescriptionNotesVo.getBirthday())));
                        }
                    }
                    if (queryPrescriptionNotesVo.getSelfPay() > 0) {
                        queryPrescriptionNotesVo.setNature("自费");
                    }
                    BigDecimal drugTotalFee = new BigDecimal(0);
                    List<QueryPrescriptionNotesVo.ChineseMedicineListBean> chineseMedicineList = queryPrescriptionNotesVo.getChineseMedicineList();
                    List<QueryPrescriptionNotesVo.DrugListBean> drugList = queryPrescriptionNotesVo.getDrugList();
                    //把上层结构拷贝到下层
                    if (CommonUtils.isNotEmpty(drugList)) {
                        for (QueryPrescriptionNotesVo.DrugListBean drugListBean : drugList) {
                            drugListBean.setClinicDept(queryPrescriptionNotesVo.getClinicDept());
                            drugListBean.setClinicDoc(queryPrescriptionNotesVo.getClinicDoc());
                            drugListBean.setDoctorName(queryPrescriptionNotesVo.getClinicDoc());
                            drugListBean.setAuditorName(drugListBean.getAuditDoctorName());
                            drugListBean.setLocalOrgId(queryPrescriptionNotesVo.getLocalOrgId());
                            drugListBean.setOrgId(queryPrescriptionNotesVo.getOrgId());
                            drugListBean.setOrgName(queryPrescriptionNotesVo.getOrgName());
                            drugListBean.setSeal(seal);


                            if (CommonUtils.isEmpty(drugListBean.getPhoneNo())) {
                                drugListBean.setPhoneNo(queryPrescriptionNotesVo.getPhoneNo());
                            }
                            if (CommonUtils.isEmpty(drugListBean.getAddress())) {
                                drugListBean.setAddress(queryPrescriptionNotesVo.getAddress());
                            }
                            if (CommonUtils.isEmpty(drugListBean.getClinicDoc())) {
                                drugListBean.setDoctorName(queryPrescriptionNotesVo.getClinicDoc());
                            }
                            if (CommonUtils.isEmpty(drugListBean.getPrescriptionDate())) {
                                drugListBean.setClinicTime(queryPrescriptionNotesVo.getClinicTime());
                            } else {
                                drugListBean.setClinicTime(drugListBean.getPrescriptionDate());
                            }
                            drugListBean.setSexCode(queryPrescriptionNotesVo.getSexCode());
                            drugListBean.setAge(queryPrescriptionNotesVo.getAge());
                            drugListBean.setBirthday(queryPrescriptionNotesVo.getBirthday());
                            drugListBean.setPatientMedicalCardNumber(queryPrescriptionNotesVo.getPatientMedicalCardNumber());

                            drugListBean.setPersonName(person.getPersonName());
                            drugListBean.setIdCardNo(queryPrescriptionNotesVo.getIdCardNo());
                            drugListBean.setSexCode(person.getSex());
                            drugListBean.setClinicSymp(queryPrescriptionNotesVo.getClinicSymp());


                            BigDecimal totalFee = new BigDecimal(0);
                            for (QueryPrescriptionNotesVo.DrugListBean.DrugDetailsBean drugDetailsBean : drugListBean.getDrugDetails()) {
                                drugDetailsBean.setQuantity(drugDetailsBean.getQuantity());
                                double price = drugDetailsBean.getPrice();
                                BigDecimal drugDetailTotalFee = new BigDecimal(price).multiply(new BigDecimal(drugDetailsBean.getQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP));
                                totalFee = totalFee.add(drugDetailTotalFee);
                                drugTotalFee = drugTotalFee.add(drugDetailTotalFee);
                            }
                            drugListBean.setTotalFee(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                            if (drugTotalFee.doubleValue() > 0) {
                                drugListBean.setNature("自费");
                            }
                        }
                    }

                    //把上层结构拷贝到下层
                    if (CommonUtils.isNotEmpty(chineseMedicineList)) {
                        for (QueryPrescriptionNotesVo.ChineseMedicineListBean chineseMedicineListBean : chineseMedicineList) {
                            chineseMedicineListBean.setClinicDept(queryPrescriptionNotesVo.getClinicDept());
                            chineseMedicineListBean.setClinicDoc(queryPrescriptionNotesVo.getClinicDoc());
                            chineseMedicineListBean.setDoctorName(queryPrescriptionNotesVo.getClinicDoc());
                            chineseMedicineListBean.setAuditorName(chineseMedicineListBean.getAuditDoctorName());
                            chineseMedicineListBean.setLocalOrgId(queryPrescriptionNotesVo.getLocalOrgId());
                            chineseMedicineListBean.setOrgId(queryPrescriptionNotesVo.getOrgId());
                            chineseMedicineListBean.setSeal(seal);

                            if (CommonUtils.isEmpty(chineseMedicineListBean.getPhoneNo())) {
                                chineseMedicineListBean.setPhoneNo(queryPrescriptionNotesVo.getPhoneNo());
                            }
                            if (CommonUtils.isEmpty(chineseMedicineListBean.getAddress())) {
                                chineseMedicineListBean.setAddress(queryPrescriptionNotesVo.getAddress());
                            }
                            if (CommonUtils.isEmpty(chineseMedicineListBean.getDoctorName())) {
                                chineseMedicineListBean.setDoctorName(queryPrescriptionNotesVo.getClinicDoc());
                            }
                            if (CommonUtils.isEmpty(chineseMedicineListBean.getPrescriptionDate())) {
                                chineseMedicineListBean.setClinicTime(queryPrescriptionNotesVo.getClinicTime());
                            } else {
                                chineseMedicineListBean.setClinicTime(chineseMedicineListBean.getPrescriptionDate());
                            }
                            chineseMedicineListBean.setSexCode(queryPrescriptionNotesVo.getSexCode());
                            chineseMedicineListBean.setAge(queryPrescriptionNotesVo.getAge());
                            chineseMedicineListBean.setBirthday(queryPrescriptionNotesVo.getBirthday());
                            chineseMedicineListBean.setPatientMedicalCardNumber(queryPrescriptionNotesVo.getPatientMedicalCardNumber());


                            chineseMedicineListBean.setPersonName(person.getPersonName());
                            chineseMedicineListBean.setIdCardNo(queryPrescriptionNotesVo.getIdCardNo());
                            chineseMedicineListBean.setSexCode(person.getSex());
                            chineseMedicineListBean.setClinicSymp(queryPrescriptionNotesVo.getClinicSymp());

                            BigDecimal totalFee = new BigDecimal(0);
                            for (QueryPrescriptionNotesVo.ChineseMedicineListBean.MedicineListBean medicineListBean : chineseMedicineListBean.getMedicineList()) {
                                medicineListBean.setQuantity(medicineListBean.getQuantity());
                                double price = medicineListBean.getPrice();
                                BigDecimal medicineTotalFee = new BigDecimal(price).multiply(new BigDecimal(medicineListBean.getQuantity()).setScale(2, BigDecimal.ROUND_HALF_UP));
                                totalFee = totalFee.add(medicineTotalFee.multiply(new BigDecimal(chineseMedicineListBean.getTotalMedicine())));
                                drugTotalFee = drugTotalFee.add(medicineTotalFee.multiply(new BigDecimal(chineseMedicineListBean.getTotalMedicine())));
                            }
                            chineseMedicineListBean.setTotalFee(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                            if (drugTotalFee.doubleValue() > 0) {
                                chineseMedicineListBean.setNature("自费");
                            }
                        }
                    }
                    queryPrescriptionNotesVo.setTotalPay(drugTotalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    queryPrescriptionNotesVo.setSelfPay(drugTotalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
            } catch (ControllerException e) {
                throw new ControllerException(e.getMessage());
            } catch (Throwable throwable) {
                throwable.printStackTrace();
                throw new ControllerException("获取健康档案信息详情失败");
            }
        }

        return queryPrescriptionNotesVo;
    }

    /**
     * 组装诊间支付处方笺
     */
    private void buildPrescriptionNotesVo(QueryPrescriptionNotesVo queryPrescriptionNotesVo, String type, ConsultAsk consultAsk, Organization organization, PrescriptionResponseTemporary prescriptionResponse) {
        //中药处方列表
        List<QueryPrescriptionNotesVo.ChineseMedicineListBean> chineseMedicineList = null;
        //中药处方
        QueryPrescriptionNotesVo.ChineseMedicineListBean chineseMedicineListBean = null;
        //中药处方药品列表
        List<QueryPrescriptionNotesVo.ChineseMedicineListBean.MedicineListBean> medicineList = null;
        //中药处方药品
        QueryPrescriptionNotesVo.ChineseMedicineListBean.MedicineListBean medicineListBean;
        //西药、中成药处方列表
        List<QueryPrescriptionNotesVo.DrugListBean> drugListBeanList = null;
        //西药、中成药处方
        QueryPrescriptionNotesVo.DrugListBean drugListBean;
        //西药、中成药处方药品列表
        List<QueryPrescriptionNotesVo.DrugListBean.DrugDetailsBean> drugDetailsBeanList = null;
        //西药、中成药处方药品
        QueryPrescriptionNotesVo.DrugListBean.DrugDetailsBean drugDetailsBean;
        BigDecimal drugTotalFee = new BigDecimal(0);
        if (CommonUtils.isNotEmpty(prescriptionResponse)) {


            queryPrescriptionNotesVo.setPatientMedicalCardNumber(prescriptionResponse.getMedicalCardId());
            queryPrescriptionNotesVo.setClinicSymp(prescriptionResponse.getClinicalDiagnose());
            queryPrescriptionNotesVo.setAddress(prescriptionResponse.getAddress());
            drugListBeanList = new ArrayList<>();
            chineseMedicineList = new ArrayList<>();
            //中药处方
            if (PrescriptionTypeEnum.CHINESE_MEDICINE.getTitle().equals(prescriptionResponse.getPrescriptionType())) {
                chineseMedicineListBean = new QueryPrescriptionNotesVo.ChineseMedicineListBean();
                if (null != prescriptionResponse.getPrescriptionDate()) {
                    chineseMedicineListBean.setClinicTime(prescriptionResponse.getPrescriptionDate());
                }
                chineseMedicineListBean.setClinicDept(prescriptionResponse.getDepartmentName());
                chineseMedicineListBean.setClinicDoc(prescriptionResponse.getPrescriptionDoctorName());
                chineseMedicineListBean.setLocalOrgId(organization.getLocalOrgId());
                chineseMedicineListBean.setOrgId(organization.getOrgId());
                chineseMedicineListBean.setOrgName(organization.getFullName());
                chineseMedicineListBean.setPersonName(queryPrescriptionNotesVo.getPersonName());
                chineseMedicineListBean.setIdCardNo(queryPrescriptionNotesVo.getIdCardNo());
                chineseMedicineListBean.setPhoneNo(queryPrescriptionNotesVo.getPhoneNo());
                chineseMedicineListBean.setSexCode(queryPrescriptionNotesVo.getSexCode());
                chineseMedicineListBean.setClinicSymp(queryPrescriptionNotesVo.getClinicSymp());
                chineseMedicineListBean.setAge(queryPrescriptionNotesVo.getAge());
                chineseMedicineListBean.setPatientMedicalCardNumber(queryPrescriptionNotesVo.getPatientMedicalCardNumber());
                chineseMedicineListBean.setAddress(queryPrescriptionNotesVo.getAddress());
                chineseMedicineListBean.setBirthday(queryPrescriptionNotesVo.getBirthday());
                chineseMedicineListBean.setPatientMedicalCardNumber(queryPrescriptionNotesVo.getPatientMedicalCardNumber());
                chineseMedicineListBean.setNature("自费");

                chineseMedicineListBean.setPrescriptionId(prescriptionResponse.getPrescriptionNumber());
                chineseMedicineListBean.setPrescriptionType(prescriptionResponse.getPrescriptionType());
                chineseMedicineListBean.setClinicSymp(prescriptionResponse.getDiagnosticName());
                chineseMedicineListBean.setTotalMedicine(prescriptionResponse.getNumberOfPackets() == null ? 0 : Integer.valueOf(prescriptionResponse.getNumberOfPackets()));

                chineseMedicineListBean.setSeal(IMG_UPLOAD_URL + "/" + organization.getSealFileId());
                //开方医生

//                DoctInfo doctor = doctorInfoService.getDocInfo(consultAsk.getDoctorId() == null ? "" : consultAsk.getDoctorId());
//                if (null != doctor) {
                //开方医生姓名
                chineseMedicineListBean.setDoctorName(prescriptionResponse.getPrescriptionDoctorName());
//                    //开方医生签名
//                    chineseMedicineListBean.setPrescriptionDoctorSignature(doctor.getDoctorSignature());
//                } else {
//                    //开方医生姓名
//                    chineseMedicineListBean.setDoctorName(prescriptionResponse.getPrescriptionDoctorName());
//                }
                //审方药师姓名
                chineseMedicineListBean.setAuditorName(prescriptionResponse.getAuditor());

                if (Constants.THREE.toString().equals(type)) {
                    chineseMedicineListBean.setOrderStatus("0");
                } else {
                    chineseMedicineListBean.setOrderStatus("1");
                }
                //药品列表
                if (CommonUtils.isNotEmpty(prescriptionResponse.getPrescriptionDrugList())) {
                    medicineList = new ArrayList<>();
                    BigDecimal totalFee = new BigDecimal(0);
                    for (PrescriptionDrugTemp odsPrescriptionDrug : prescriptionResponse.getPrescriptionDrugList()) {
                        medicineListBean = new QueryPrescriptionNotesVo.ChineseMedicineListBean.MedicineListBean();
                        medicineListBean.setDrugId(String.valueOf(odsPrescriptionDrug.getDrugCode()));
                        medicineListBean.setDrugName(odsPrescriptionDrug.getDrugName());
                        medicineListBean.setQuantity(Double.valueOf(String.valueOf(odsPrescriptionDrug.getQuantity() == null ? 0 : odsPrescriptionDrug.getQuantity())));
                        medicineListBean.setPackUnit(odsPrescriptionDrug.getUnit());
                        medicineListBean.setDecoctionCode(odsPrescriptionDrug.getDecoctionCode());
                        medicineListBean.setDecoctionName(odsPrescriptionDrug.getDecoctionName());
                        medicineListBean.setSpecification(odsPrescriptionDrug.getSpecifications());
                        double price = odsPrescriptionDrug.getPrice() == null ? 0 : Double.valueOf(odsPrescriptionDrug.getPrice());
                        medicineListBean.setPrice(price);
                        chineseMedicineListBean.setFrequencyName(odsPrescriptionDrug.getFrequencyName());
                        chineseMedicineListBean.setFrequencyCode(odsPrescriptionDrug.getFrequencyCode());
                        chineseMedicineListBean.setUsageCode(odsPrescriptionDrug.getUsageCode());
                        chineseMedicineListBean.setTreatment(odsPrescriptionDrug.getUsageName());
                        medicineList.add(medicineListBean);
                        BigDecimal medicineTotalFee = new BigDecimal(price).multiply(new BigDecimal(Double.valueOf(String.valueOf(odsPrescriptionDrug.getQuantity() == null ? 0 : odsPrescriptionDrug.getQuantity())))).setScale(2, BigDecimal.ROUND_HALF_UP);
                        totalFee = totalFee.add(medicineTotalFee.multiply(BigDecimal.valueOf(prescriptionResponse.getNumberOfPackets() == null ? 0 : Double.valueOf(prescriptionResponse.getNumberOfPackets()))));
                        drugTotalFee = drugTotalFee.add(medicineTotalFee.multiply(BigDecimal.valueOf(prescriptionResponse.getNumberOfPackets() == null ? 0 : Double.valueOf(prescriptionResponse.getNumberOfPackets()))));
                    }
                    chineseMedicineListBean.setTotalFee(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                chineseMedicineListBean.setMedicineList(medicineList);
                chineseMedicineList.add(chineseMedicineListBean);
            } else {
                drugListBean = new QueryPrescriptionNotesVo.DrugListBean();

                drugListBean.setPersonName(queryPrescriptionNotesVo.getPersonName());
                if (null != prescriptionResponse.getPrescriptionDate()) {
                    drugListBean.setClinicTime(prescriptionResponse.getPrescriptionDate());
                }
                drugListBean.setClinicDept(prescriptionResponse.getDepartmentName());
                drugListBean.setClinicDoc(prescriptionResponse.getPrescriptionDoctorName());
                drugListBean.setClinicSymp(queryPrescriptionNotesVo.getClinicSymp());
                drugListBean.setPatientMedicalCardNumber(queryPrescriptionNotesVo.getPatientMedicalCardNumber());
                drugListBean.setLocalOrgId(organization.getLocalOrgId());
                drugListBean.setOrgId(organization.getOrgId());
                drugListBean.setIdCardNo(queryPrescriptionNotesVo.getIdCardNo());
                drugListBean.setPhoneNo(queryPrescriptionNotesVo.getPhoneNo());
                drugListBean.setOrgName(organization.getFullName());
                drugListBean.setSexCode(queryPrescriptionNotesVo.getSexCode());
                drugListBean.setAge(queryPrescriptionNotesVo.getAge());
                drugListBean.setAddress(queryPrescriptionNotesVo.getAddress());
                drugListBean.setBirthday(queryPrescriptionNotesVo.getBirthday());
                drugListBean.setPatientMedicalCardNumber(queryPrescriptionNotesVo.getPatientMedicalCardNumber());
                drugListBean.setNature("自费");

                drugListBean.setPrescriptionId(prescriptionResponse.getPrescriptionNumber());
                drugListBean.setPrescriptionType(prescriptionResponse.getPrescriptionType());

                drugListBean.setSeal(IMG_UPLOAD_URL + "/" + organization.getSealFileId());
                //开方医生
//                DoctInfo doctor = doctorInfoService.getDocInfo(consultAsk.getDoctorId() == null ? "" : consultAsk.getDoctorId());
//                if (null != doctor) {
                //开方医生姓名
                drugListBean.setDoctorName(prescriptionResponse.getPrescriptionDoctorName());
//                    //开方医生签名
//                    drugListBean.setPrescriptionDoctorSignature(doctor.getDoctorSignature());
//                } else {
//                    //开方医生姓名
//                    drugListBean.setDoctorName(prescriptionResponse.getPrescriptionDoctorName());
//                }

                //审方药师姓名
                drugListBean.setAuditorName(prescriptionResponse.getAuditor());

                if (Constants.THREE.toString().equals(type)) {
                    drugListBean.setOrderStatus("0");
                } else {
                    drugListBean.setOrderStatus("1");
                }
                //药品列表
                if (CommonUtils.isNotEmpty(prescriptionResponse.getPrescriptionDrugList())) {
                    drugDetailsBeanList = new ArrayList<>();
                    BigDecimal totalFee = new BigDecimal(0);
                    for (PrescriptionDrugTemp odsPrescriptionDrug : prescriptionResponse.getPrescriptionDrugList()) {
                        drugDetailsBean = new QueryPrescriptionNotesVo.DrugListBean.DrugDetailsBean();
                        drugDetailsBean.setDrugId(String.valueOf(odsPrescriptionDrug.getDrugCode()));
                        drugDetailsBean.setDrugName(odsPrescriptionDrug.getDrugName());
                        drugDetailsBean.setQuantity(Double.valueOf(String.valueOf(odsPrescriptionDrug.getQuantity() == null ? 0 : odsPrescriptionDrug.getQuantity())));
                        drugDetailsBean.setPackUnit(odsPrescriptionDrug.getUnit());
                        drugDetailsBean.setFrequencyName(odsPrescriptionDrug.getFrequencyName());
                        drugDetailsBean.setFrequencyCode(odsPrescriptionDrug.getFrequencyCode());
                        drugDetailsBean.setUsageName(odsPrescriptionDrug.getUsageName());
                        drugDetailsBean.setUsageCode(odsPrescriptionDrug.getUsageCode());
                        drugDetailsBean.setDose(odsPrescriptionDrug.getDose() == null ? "0" : odsPrescriptionDrug.getDose());
                        drugDetailsBean.setDoseUnit(odsPrescriptionDrug.getDoseUnit());
                        drugDetailsBean.setSpecification(odsPrescriptionDrug.getSpecifications());
                        double price = odsPrescriptionDrug.getPrice() == null ? 0 : Double.valueOf(odsPrescriptionDrug.getPrice());
                        drugDetailsBean.setPrice(price);
                        drugDetailsBeanList.add(drugDetailsBean);
                        BigDecimal drugDetailTotalFee = new BigDecimal(price).multiply(new BigDecimal(Double.valueOf(String.valueOf(odsPrescriptionDrug.getQuantity() == null ? 0 : odsPrescriptionDrug.getQuantity())))).setScale(2, BigDecimal.ROUND_HALF_UP);
                        totalFee = totalFee.add(drugDetailTotalFee);
                        drugTotalFee = drugTotalFee.add(drugDetailTotalFee);
                    }
                    drugListBean.setTotalFee(totalFee.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                }
                drugListBean.setDrugDetails(drugDetailsBeanList);
                drugListBeanList.add(drugListBean);
            }
        }
        if (CommonUtils.isNotEmpty(chineseMedicineList)) {
            queryPrescriptionNotesVo.setChineseMedicineList(chineseMedicineList);
        }
        if (CommonUtils.isNotEmpty(drugListBeanList)) {
            queryPrescriptionNotesVo.setDrugList(drugListBeanList);
        }
        queryPrescriptionNotesVo.setDrugTotalFee(drugTotalFee.doubleValue());
    }

    /**
     * @description: 获取快递物流信息
     * @author: chenJij@bsoft.com.cn
     * @date: 2020/1/4 14:23
     */
    @RpcService
    public List<Map<String, Object>> queryDrugOrderExpressInfoList(QueryDrugOrderExpressInfoListQo qo) throws ControllerException {
        if (CommonUtils.isEmpty(qo.getOrderId())) {
            throw new ControllerException("订单id不能为空");
        }
        List<Map<String, Object>> expressList = Lists.newArrayList();
        List<ExpreeInfoVo> expressInfoVoList = queryExpressInfo(qo.getOrderId());
        if (CommonUtils.isEmpty(expressInfoVoList)) {
            return expressList;
        }
        for (ExpreeInfoVo expreeInfoVo : expressInfoVoList) {
            Map<String, Object> map = Maps.newHashMap();
            map.put("expressUrl", expressQueryUrl + "?com=" + expreeInfoVo.getExpreeCompanyCode() + "&nu=" + expreeInfoVo.getExpreeNumber());
            map.put("logisticNo", expreeInfoVo.getExpreeNumber());
            expressList.add(map);
        }
        return expressList;
    }

    /*
     *解密国产化加密存储
     */
    public static Person decryptData(Person person) {
        //国产化加密存储 解密
        person.setPhoneNo(SM4Utils.decryptData_ECB(person.getPhoneNo()));
        person.setAddress(SM4Utils.decryptData_ECB(person.getAddress()));
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(person.getRegisteredAddress())) {
            person.setRegisteredAddress(SM4Utils.decryptData_ECB(person.getRegisteredAddress()));
        }
        person.setWorkPlace(SM4Utils.decryptData_ECB(person.getWorkPlace()));

        if (person.getCertificate() != null && person.getCertificate().getCertificateNo() != null) {
            //国产化加密证件号 解密
            person.getCertificate().setCertificateNo(SM4Utils.decryptData_ECB(person.getCertificate().getCertificateNo()));
        }

        return person;
    }
}
